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 == nullptr || head->next == nullptr){
return head;
}
auto *slow = head;
auto *fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
auto head2 = slow->next;
slow->next = NULL;
auto left = sortList(head);
auto right = sortList(head2);
return merge(left,right);
}
private:
ListNode *merge(ListNode *l1, ListNode *l2) {
ListNode dummy(-1);
for (ListNode *p = &dummy; l1 || l2; p = p->next) {
int val1 = l1?l1->val:INT_MAX;
int val2 = l2?l2->val:INT_MAX;
if (val1<val2) {
p->next = l1;
l1 = l1->next;
} else {
p->next = l2;
l2 = l2->next;
}
}
return dummy.next;
}
};