Sort a linked list in O(n log n) time using constant space complexity.
基于binary merge sort算法的思想实现。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next){
return head;
}
ListNode * slow = head;
ListNode * fast = head;
while(fast->next && fast->next->next){
slow = slow->next;
fast = fast->next->next;
}
fast = slow->next;
slow->next = NULL;
slow = head;
ListNode * left = sortList(slow);
ListNode * right = sortList(fast);
return merge(left, right);
}
ListNode * merge(ListNode * left, ListNode * right){
ListNode dummy(0);
ListNode * cur = &dummy;
while(left && right){
if(left->val < right->val){
cur->next = left;
left = left->next;
}else{
cur->next = right;
right = right->next;
}
cur = cur->next;
}
if(left){
cur->next = left;
}
if(right){
cur->next = right;
}
return dummy.next;
}
};