Sort a linked list in O(n log n) time using constant space complexity.
class Solution {
public:
ListNode *sortList(ListNode *head)
{
if (0 == head || 0 == head->next) return head;
ListNode* slow = head;
ListNode* fast = head;
while (0 != fast->next && 0 != fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
}
ListNode* head2 = sortList(slow->next);
slow->next = 0;
ListNode* head1 = sortList(head);
ListNode* res = 0;
if (head1->val <= head2->val)
{
res = head1;
head1 = head1->next;
}
else
{
res = head2;
head2 = head2->next;
}
ListNode* tmp = res;
while (0 != head1 && 0 != head2)
{
if (head1->val <= head2->val)
{
tmp->next = head1;
head1 = head1->next;
}
else
{
tmp->next = head2;
head2 = head2->next;
}
tmp = tmp->next;
}
tmp->next = (head1 == 0 ? head2 : head1);
return res;
}
};