Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
class Solution {
public:
ListNode* sortList(ListNode* head) {
/*
* 空间复杂度为O(1) 不能构建辅助数组排序
* 采用归并排序 第一步将链表从中间断开 成两半(快慢指针法)
* 对两个断开后的链表 进行递归的的归并排序 每次取出一个头元素 进行判断
* 1 2 3 4 5 6
* pre slow fast
* 除了pre 和fast 外设pre 方便断链
* */
if(!head || !head->next) return head;
ListNode *pre=head, *slow=head, *fast=head;
while(fast && fast->next){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next = NULL; // 断开
//return mergesort(head, slow);
// sortlist 是一个折半的划分 通过mergesort 进行融合
return mergesort(sortList(head), sortList(slow));
}
ListNode *mergesort(ListNode *l1, ListNode* l2){
// 对l1 或者 l2摘下来的第一个节点进行归并排序
if(!l1) return l2;
if(!l2) return l1;
if(l1->val < l2->val){
l1->next = mergesort(l1->next, l2);
return l1;
}
else{
l2->next = mergesort(l1, l2->next);
return l2;
}
}
};