Insertion Sort List

Sort a linked list using insertion sort.

 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         ListNode dummy(INT_MIN);
13         dummy.next = head;
14         ListNode* cur = &dummy;
15         while(cur->next) {
16             if(cur->next->val >= cur->val)
17                 cur = cur->next;
18             else 
19                 insert(&dummy, cur, cur->next);
20         }
21         return dummy.next;
22     }
23     
24     void insert(ListNode* head, ListNode* tail, ListNode* node) 
25     {
26         ListNode* cur = head;
27         while(cur->next->val <= node->val && cur != tail) {
28             cur = cur->next;
29         }
30         tail->next = node->next;
31         node->next = cur->next;
32         cur->next = node;
33     }
34 };

 

 

posted @ 2014-04-15 22:56  beehard  阅读(106)  评论(0编辑  收藏  举报