问题
归并排序链表,常数级别空间复杂度
算法:快慢指针,归并排序,链表合并
经典题,关键点在于找到归并的中点。使用快慢指针,当快指针到头,满指针恰好就到中点了。
递归边界即单个节点或者空节点。
有序链表合并用三个指针搞定
时间复杂度
$O(NlogN)$
代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !(head->next)) return head;
ListNode *f = head->next, *s = head;
while(f && f->next){
f = f->next->next;
s = s->next;
}
ListNode *t = s->next;
s->next = nullptr;
head = sortList(head);
t = sortList(t);
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *p = dummy;
while(head && t){
if(head->val <= t->val){
p->next = head;
head = head->next;
}else{
p->next = t;
t = t->next;
}
p = p->next;
}
p->next = head ? head : t;
return dummy->next;
}
};