Sort a linked list in O(n log n) time using constant space complexity.
Solution:
Code:
<span style="font-size:14px;">/**
* 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;
//attention
ListNode *fast = head->next, *slow = head;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
//attention
fast = slow->next;
slow->next = NULL;
slow = sortList(fast);
fast = sortList(head);
ListNode *begin, *end;
if (fast->val < slow->val) {
begin = fast;
end = fast;
fast = fast->next;
} else {
begin = slow;
end = slow;
slow = slow->next;
}
while (fast != NULL && slow != NULL) {
if (fast->val < slow->val) {
end->next = fast;
end = fast;
fast = fast->next;
} else {
end->next = slow;
end = slow;
slow = slow->next;
}
}
if (fast != NULL) end->next = fast;
else end->next = slow;
return begin;
}
};</span>