LeetCode148 Sort List

Sort a linked list in O(n log n) time using constant space complexity. (Medium)html

 

分析:數組

由於題目要求複雜度爲O(nlogn),故能夠考慮歸併排序的思想。
歸併排序的通常步驟爲:
1)將待排序數組(鏈表)取中點並一分爲二;
2)遞歸地對左半部分進行歸併排序;
3)遞歸地對右半部分進行歸併排序;
4)將兩個半部分進行合併(merge),獲得結果。
 
因此對應此題目,能夠劃分爲三個小問題:
1)找到鏈表中點 (快慢指針思路,快指針一次走兩步,慢指針一次走一步,快指針在鏈表末尾時,慢指針剛好在鏈表中點);
2)寫出merge函數,即如何合併鏈表。 (能夠參見 merge-two-sorted-lists 一題)
3)寫出mergesort函數,實現上述步驟。
 
代碼:
 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* findMiddle(ListNode* head){
12         ListNode* chaser = head;
13         ListNode* runner = head->next;
14         while(runner != NULL && runner->next != NULL){
15             chaser = chaser->next;
16             runner = runner->next->next;
17         }
18         return chaser;
19     }
20      
21  ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
22         if(l1 == NULL){
23             return l2;
24         }
25         if(l2 == NULL){
26             return l1;
27         }
28         ListNode* dummy = new ListNode(0);
29         ListNode* head = dummy;
30         while(l1 != NULL && l2 != NULL){
31             if(l1->val > l2->val){
32                 head->next = l2;
33                 l2 = l2->next;
34             }
35             else{
36                 head->next = l1;
37                 l1 = l1->next;
38             }
39             head = head->next;
40         }
41         if(l1 == NULL){
42             head ->next = l2;
43         }
44         if(l2 == NULL){
45             head->next = l1;
46         }
47         return dummy->next;
48     }
49      
50     ListNode* sortList(ListNode* head) {
51         if(head == NULL || head ->next == NULL){
52             return head;
53         }
54         ListNode* middle = findMiddle(head);
55         ListNode* right = sortList(middle->next);
56         middle -> next = NULL;
57         ListNode* left = sortList(head);
58         return mergeTwoLists(left, right);
59     }
60 };
相關文章
相關標籤/搜索