Sort List--leetcode

问题描述:Sort a linked list in O(n log n) time using constant space complexity.

由于问题要求复杂度为O(nlogn),所以按常规方法排序无法达到该复杂度,可采用归并排序实现。

设立两个快慢指针,找到中间节点位置作归并排序即可,实现代码如下:

 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         if (NULL == head || NULL == head->next)
13             return head;
14         ListNode *slow = head, *fast = head;
15         while (slow && fast && fast->next && fast->next->next)
16         {
17             slow = slow->next;
18             fast = fast->next->next;
19         }
20         fast = slow->next;
21         slow->next = NULL;
22         slow = head;
23         slow = sortList(slow);
24         fast = sortList(fast);
25         
26         return mergeTwoLists(slow, fast);
27     }
28     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2){
29         ListNode *head = new ListNode(0);
30         assert(head);
31         ListNode *pCurr = head;
32         
33         while (l1 != NULL && l2 != NULL)
34         {
35             if (l1->val < l2->val)
36             {
37                 pCurr->next = l1;
38                 l1 = l1->next;
39             }
40             else
41             {
42                 pCurr->next = l2;
43                 l2 = l2->next;
44             }
45             pCurr = pCurr->next;
46         }
47         if (l1 != NULL)
48             pCurr->next = l1;
49         if (l2 != NULL)
50             pCurr->next = l2;
51         pCurr = head->next;
52         delete head;
53         head = pCurr;
54         return head;
55     }
56 };

 

posted @ 2014-09-03 17:00  独行中随行  阅读(394)  评论(0)    收藏  举报