Sort a linked list in O(n log n) time using constant space complexity.
题意
对链表进行排序,时间复杂度O(n log n),空间复杂度为常数。
题解
用归并算法,前面一题的函数可以直接复制过来使用: [leetcode] 【排序】 21. Merge Two Sorted Lists
将链表分为两部分,归并即可。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode *fast=head,*slow=head;
while(fast->next!=NULL&&fast->next->next!=NULL)
{
fast=fast->next->next;
slow=slow->next;
}
ListNode *l2=slow->next;
slow->next=NULL;
ListNode *l1=head;
l1=sortList(l1);
l2=sortList(l2);
return mergeTwoLists(l1,l2);
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if(!l1) return l2;
if(!l2) return l1;
ListNode newstart(-1);
ListNode* p=&newstart;
for(;l1!=NULL&&l2!=NULL;p=p->next)
{
if(l1->val<l2->val)
{
p->next=l1;
l1=l1->next;
}
else
{
p->next=l2;
l2=l2->next;
}
}
p->next=l1!=NULL ? l1 :l2;
return newstart.next;
}
};