【题目描述】Sort a linked list in O(n log n) time using constant space complexity.链表排序
【解题思路】因为题目要求复杂度为O(nlogn),故可以考虑归并排序的思想。归并排序的一般步骤为:
1)将待排序数组(链表)取中点并一分为二;
2)递归地对左半部分进行归并排序;
3)递归地对右半部分进行归并排序;
4)将两个半部分进行合并(merge),得到结果。
所以对应此题目,可以划分为三个小问题:
1)找到链表中点 (快慢指针思路,快指针一次走两步,慢指针一次走一步,快指针在链表末尾时,慢指针恰好在链表中点);
2)写出merge函数,即如何合并链表。
3)写出mergesort函数,实现上述步骤。
【考察内容】归并排序,分治法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeList(ListNode *la,ListNode *lb){
if(la==NULL)
return lb;
if(lb==NULL)
return la;
ListNode *head=NULL;
if(la->val<lb->val){
head=la;
head->next=mergeList(la->next,lb);
}else{
head=lb;
head->next=mergeList(la,lb->next);
}
return head;
}
ListNode *sortList(ListNode *head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *s=head;
ListNode *f=head->next;
while(f&&f->next){
s=s->next;
f=f->next->next;
}
ListNode *p=s->next;
s->next=NULL;//将链表从中间断开
return mergeList(sortList(head),sortList(p));
}
};