Sorted List 排序链表
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
输入:
4->2->1->3
输出:
1->2->3->4
方法一:归并排序
归并排序的核心是一个 merge() 函数,其主要是合并两个有序链表,这个在 LeetCode 中也有单独的题目 21.Merge Two Sorted Lists合并两个有序链表
归并排序的核心其实是分治法 Divide and Conquer,就是将链表从中间断开,分成两部分,左右两边再分别调用排序的递归函数 sortList(),得到各自有序的链表后,再进行 merge(),这样整体就是有序的了。
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head||!head->next) return head;
ListNode *fast=head,*slow=head,*pre=head;
while(fast&&fast->next){
pre=slow;
fast=fast->next->next;
slow=slow->next;
}
pre->next=NULL;
return merge(sortList(head),sortList(slow));
}
ListNode*merge(ListNode* l1,ListNode *l2){
if(!l1) return l2;
if(!l2) return l1;
if(l1->val<l2->val){
l1->next=merge(l1->next,l2);
return l1;
}
else{
l2->next=merge(l1,l2->next);
return l2;
}
}
};
注意:merge()函数还有另外一种写法(参见21题)
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode *dummy = new ListNode(-1);
ListNode *cur = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1) cur->next = l1;
if (l2) cur->next = l2;
return dummy->next;
}