问题描述如下:
Sort a linked list in O(n log n) time using constant space complexity.
cpp代码如下:
class Solution {
public:
ListNode *sortList(ListNode *head) {
if(head==NULL||head->next==NULL)return head;
ListNode *s=head,*f=head;
while(true){
f=f->next;
if(f==NULL)break;
f=f->next;
if(f==NULL)break;
s=s->next;
}
f=s->next;
s->next=NULL;
s=sortList(head);
f=sortList(f);
if(s->val<=f->val){
head=s;
s=s->next;
}else{
head=f;
f=f->next;
}
ListNode* tail=head;
while(s!=NULL&&f!=NULL){
if(s->val<=f->val){
tail->next=s;
tail=s;
s=s->next;
}else{
tail->next=f;
tail=f;
f=f->next;
}
}
if(s!=NULL)tail->next=s;
else tail->next=f;
return head;
}
};