Sort List

Sort a linked list in O(nlogn) time using constant space complexity.

 

 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 *sortList(ListNode *head) {
12         return sortLinkedList(head, getLength(head));
13     }
14     
15     ListNode* sortLinkedList(ListNode *&head, int N) {
16         if (N == 0) return NULL;
17         if (N == 1) {
18             ListNode* cur = head;
19             head = head->next;
20             cur->next = NULL;
21             return cur;
22         }
23         int half = N / 2;
24         ListNode* head1 = sortLinkedList(head, half);
25         ListNode* head2 = sortLinkedList(head, N - half);
26         return mergeList(head1, head2);
27     }
28     
29     ListNode* mergeList(ListNode *head1, ListNode*head2) {
30         ListNode dummy(0); dummy.next = NULL;
31         ListNode *cur = &dummy;
32         while (head1 && head2)
33         {
34             ListNode **min = head1->val < head2->val ? &head1 : &head2;
35             cur->next = *min;
36             cur = cur->next;
37             *min = (*min)->next;
38         }
39         if (!head1) cur->next = head2;
40         if (!head2) cur->next = head1;
41         return dummy.next;
42     }
43     
44     int getLength(ListNode *head) {
45         int length = 0;
46         while (head) {
47             length++;
48             head = head->next;
49         }
50         return length;
51     }
52 };

 

posted @ 2014-04-22 07:12  beehard  阅读(155)  评论(0编辑  收藏  举报