LeetCode:148. Sort List
阿新 • • 發佈:2018-11-06
連結串列排序的問題,要求時間複雜度為O(nlogn),空間複雜度為常數。
比如:
Input: 4->2->1->3
Output: 1->2->3->4
這道題的思路是用歸併排序,我們先看程式碼:
class Solution { public: ListNode* sortList(ListNode* head) { if (!head || !(head->next)) return head; auto pFast = head, pSlow = head; ListNode* pPrev = nullptr; while (pFast && pFast->next) { pPrev = pSlow; pSlow = pSlow->next; pFast = pFast->next->next; } pPrev->next = nullptr; auto p1 = sortList(head); auto p2 = sortList(pSlow); return merge(p1, p2); } private: ListNode* merge(ListNode* head1, ListNode* head2) { if (!head1) return head2; if (!head2) return head1; if (head1->val < head2->val) { head1->next = merge(head1->next, head2); return head1; } else { head2->next = merge(head1, head2->next); return head2; } } };
這裡有幾個有意思的點:
1.又是使用一快一慢兩個指標,來找到連結串列的中間位置。
2.可以將pPrev的next設為null,將原來的長連結串列切斷為兩個分別以head和pSlow開頭的短連結串列。
3.merge()函式,我覺得我這樣用遞迴來寫還是比較自然優雅的。
所以這道題的兩個函式都用到了遞迴,它們都是與自己遞迴,互不相干。