Sort a linked list in O(n log n) time using constant space complexity.
/**
* 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* a=head, *b=head;
while(b->next && b->next->next){
a=a->next;
b=b->next->next;
}
b=sortList(a->next);
a->next=NULL;
a=sortList(head);
ListNode* tail=NULL;
while(a && b){
if(a->val < b->val){
if(tail){
tail=tail->next=a;
}
else{
head=tail=a;
}
a=a->next;
}
else{
if(tail){
tail=tail->next=b;
}
else{
head=tail=b;
}
b=b->next;
}
}
if(a){
if(tail){
tail->next=a;
}
else{
head=tail;
}
}
else{
if(tail){
tail->next=b;
}
else{
head=b;
}
}
return head;
}
};