[Leetcode] Sort List

Sort a linked list in O(n log n) 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 *mergeSort(ListNode *l1, ListNode *l2) {
12         ListNode *head = new ListNode(-1);
13         ListNode *pos = head;
14         while (l1 != NULL && l2 != NULL) {
15             if (l1->val < l2->val) {
16                 pos->next = l1;
17                 l1 = l1->next;
18             } else {
19                 pos->next = l2;
20                 l2 = l2->next;
21             }
22             pos = pos->next;
23         }
24         if (l1 == NULL) pos->next = l2;
25         if (l2 == NULL) pos->next = l1;
26         return head->next;
27     }
28     
29     ListNode *sortList(ListNode *head) {
30         if (head == NULL || head->next == NULL) return head;
31         ListNode *slow = head, *fast = head;
32         while (fast != NULL && fast->next != NULL) {
33             if (fast->next) fast = fast->next;
34             else break;
35             if (fast->next) fast = fast->next;
36             else break;
37             if (slow) slow = slow->next;
38         }
39         ListNode *head2 = slow->next;
40         slow->next = NULL;
41         head = sortList(head);
42         head2 = sortList(head2);
43         return mergeSort(head, head2);
44     }
45 };

 

posted @ 2014-04-08 14:00  Eason Liu  阅读(137)  评论(0编辑  收藏  举报