- Sort List
中文English
Sort a linked list in O(n log n) time using constant space complexity.
Example
Example 1:
Input: 1->3->2->null
Output: 1->2->3->null
Example 2:
Input: 1->7->2->6->null
Output: 1->2->6->7->null
Challenge
Solve it by merge sort & quick sort separately.
解法1:Merge Sort
注意:
-
findMiddle()模板。
-
while后面必须用两个if, 而不是两个while!!!
而Sort Integer那题的模板里面是两个while!!!
https://blog.youkuaiyun.com/roufoo/article/details/89379984 -
sort list比sort array用merge sort的好处就是不需要再另外开空间。
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The head of linked list.
* @return: You should return the head of the sorted linked list, using constant space complexity.
*/
ListNode * sortList(ListNode * head) {
if (!head || !head->next) return head;
ListNode * mid = findMiddle(head);
ListNode * rightHead = sortList(mid->next);
mid->next = NULL;
ListNode * leftHead = sortList(head);
return merge(leftHead, rightHead);
}
private:
ListNode * findMiddle(ListNode * head) {
ListNode * slow = head, * fast = head->next;
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
return slow;
}
ListNode * merge(ListNode * head1, ListNode * head2) {
ListNode * dummy = new ListNode(0);
ListNode * p = dummy;
while(head1 && head2) {
if (head1->val < head2->val) {
p->next = head1;
head1 = head1->next;
} else {
p->next = head2;
head2 = head2->next;
}
p = p->next;
}
if (head1) {
p->next = head1;
} else {
p->next = head2;
}
return dummy->next;
}
};
解法2: Quick Sort
TBD (好像巨复杂???)