首页 > 其他 > 详细

Insertion Sort List

时间:2015-10-29 18:22:53      阅读:217      评论:0      收藏:0      [点我收藏+]

单链表的插入排序,折腾了好久一会儿,好不容易做出来,在leetcode上仅仅击败百分之十几的人,而且代码啰嗦,参考了下别人代码,提交了下面的代码接近50%

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* insertionSortList(ListNode* head) {
12         if(head == nullptr)  return head;
13         if(head->next == nullptr) return head;
14 
15         ListNode* helper = new ListNode(-1);
16         
17         ListNode* cur= head;
18         ListNode* pre;
19         ListNode* next;
20 
21         while(cur){
22             next = cur->next;
23             pre = helper;
24             
25             while(pre->next != nullptr && pre->next->val < cur->val){
26                 pre = pre -> next;
27             }
28             
29             cur->next = pre->next;
30             pre->next = cur;
31             cur = next;
32         }
33         
34         head = helper->next;
35         delete helper;
36         return head;
37     }
38 };

 

Insertion Sort List

原文:http://www.cnblogs.com/wxquare/p/4921096.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!