码迷,mamicode.com
首页 > 其他好文 > 详细

Insertion Sort List

时间:2015-10-29 18:24:52      阅读:133      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!