/** * 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) { return sortList(head, NULL); } ListNode* sortList(ListNode* head, ListNode* tail) { if (head == tail || head->next == tail) return head; ListNode *halfhead = middleList(head, tail); ListNode *h1 = sortList(head, halfhead); ListNode *h2 = sortList(halfhead, tail); return mergeList(h1, halfhead, h2, tail); } ListNode* middleList(ListNode* head, ListNode* tail) { ListNode *fast = head, *slow = head; while (fast != tail && fast->next != tail) { fast = fast->next->next; slow = slow->next; } return slow; } ListNode* mergeList(ListNode* h1, ListNode* t1, ListNode* h2, ListNode* t2) { ListNode h(0); ListNode *p = &h; while (h1 != t1 && h2 != t2) { if (h1->val > h2->val) { p->next = h2; h2 = h2->next; } else { p->next = h1; h1 = h1->next; } p = p->next; } while (h1 != t1) { p->next = h1; h1 = h1->next; p = p->next; } while (h2 != t2) { p->next = h2; h2 = h2->next; p = p->next; } p->next = t2; // don't forget to set last node's next to t2 return h.next; } };