题目描述:
Sort a linked list in O(n log n) time using constant space complexity.
用递归进行归并排序可以实现链表排序,时间复杂度O(nlogn),递归算法设计为两部分:拆分链表和归并链表。
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (head==NULL) return NULL;
if(head->next==NULL) return head;
ListNode* pre=head;
ListNode* mid=head;
ListNode* end=head;
while(end!=NULL&&end->next!=NULL)
{
pre=mid;
end=end->next->next;
mid=mid->next;
}
pre->next=NULL;
return mergeList(sortList(head),sortList(mid));
}
ListNode* mergeList(ListNode* p, ListNode* q) {
if(p==NULL&&q!=NULL) return q;
if(p!=NULL&&q==NULL) return p;
if(p==NULL&&q==NULL) return NULL;
ListNode* head=new ListNode(0);
ListNode* result=head;
while(p!=NULL&&q!=NULL)
{
if(p->val<=q->val)
{
head->next=p;
p=p->next;
}
else
{
head->next=q;
q=q->next;
}
head=head->next;
}
if(p!=NULL) head->next=p;
else if(q!=NULL) head->next=q;
return result->next;
}
};