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 || head->next == NULL) return head; ListNode *tail = head, *mid = head, *pre = head; while (tail && tail->next) { pre = mid; mid = mid->next; tail = tail->next->next; } //change pre next to null, make two sub list(head to pre, p1 to p2) pre->next = NULL; ListNode *h1 = sortList(head); ListNode *h2 = sortList(mid); return merge(h1, h2); } ListNode* merge(ListNode *h1, ListNode *h2) { if (h1 == NULL) return h2; if (h2 == NULL) return h1; if (h1->val < h2->val) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; } } };