Sort a linked list in O(n log n) time using constant space complexity.
class Solution {
public:
ListNode *sortList(ListNode *head) {
if(head == NULL || head->next == NULL) {
return head;
}
ListNode * slow = head;
ListNode * fast = head;
while(slow->next != NULL && fast->next->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
ListNode * mid = slow->next;
slow->next = NULL;
head = sortList(head);
mid = sortList(mid);
return merge(head, mid);
}
ListNode *merge(ListNode *headone, ListNode *headtwo) {
if(headone == NULL)
return headtwo;
if(headtwo == NULL)
return headone;
ListNode * headnew = new ListNode(-1);
ListNode * last = headnew;
while(headone != NULL && headtwo != NULL) {
if(headone->val < headtwo->val) {
last->next = headone;
headone = headone->next;
}else {
last->next = headtwo;
headtwo = headtwo->next;
}
last = last->next;
}
if(headone == NULL) {
last->next = headtwo;
}
if(headtwo == NULL) {
last->next = headone;
}
return headnew->next;
}
};