Sort a linked list in O(n log n) time using constant space complexity.
// Merge sort linked list.
ListNode* mergeLists(ListNode* l1, ListNode* l2) {
if(!l2) return l1;
if(!l1) return l2;
ListNode* head = new ListNode(INT_MAX);
ListNode* p = head;
while(l1 && l2) {
if(l1->val < l2->val) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(!l1) p->next = l2;
if(!l2) p->next = l1;
p = head;
head = head->next;
delete p;
return head;
}
ListNode* sortList(ListNode* head) {
ListNode* c = head;
if(head == NULL || head->next == NULL) return head;
ListNode* a;
ListNode* b;
a = c; b = c->next;
while((b != NULL) && (b->next != NULL)) {
c = c->next; b = b->next->next;
} // get the middle pointer.
b = c->next; c->next = NULL;
return mergeLists(sortList(a), sortList(b));
}