Skip to content

Instantly share code, notes, and snippets.

Created February 26, 2014 07:00
Show Gist options
  • Save anonymous/9224939 to your computer and use it in GitHub Desktop.
Save anonymous/9224939 to your computer and use it in GitHub Desktop.
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 == NULL) {
return head;
}
return sortList(head, NULL);
}
private:
ListNode *sortList(ListNode *head, ListNode *sentinel) {
if (head->next == sentinel) { // only 1 node presents
head->next = NULL;
return head;
}
ListNode *mid;
ListNode *end;
mid = end = head;
while (end != sentinel) {
mid = mid->next;
end = end->next;
if (end == sentinel) {
break;
} else {
end = end->next;
}
}
ListNode *a = sortList(head, mid);
ListNode *b = sortList(mid, sentinel);
// INVARIANT: [head, current] are all in order
// TERMINATION: a == NULL && b == NULL
head = new ListNode(-1);
ListNode *current = head;
while (a != NULL || b != NULL) {
if (a == NULL || (b != NULL && b->val < a->val)) {
current->next = b;
b = b->next;
} else {
current->next = a;
a = a->next;
}
current = current->next;
}
current->next = NULL;
return head->next;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment