Use merge sort. Recursively call the function:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *sortList(ListNode *head) { 12 if (!head || !head->next) return head; 13 ListNode *slow = head, *fast = head; 14 while (fast->next && fast->next->next) { 15 slow = slow->next; 16 fast = fast->next->next; 17 } 18 fast = slow->next; 19 slow->next = NULL; 20 slow = sortList(head); 21 fast = sortList(fast); 22 ListNode *result = new ListNode(0); 23 ListNode *runner = result; 24 while (slow || fast) { 25 int tmp1 = INT_MAX, tmp2 = INT_MAX; 26 if (slow) { 27 tmp1 = slow->val; 28 } 29 if (fast) { 30 tmp2 = fast->val; 31 } 32 if (tmp1 < tmp2) { 33 runner->next = slow; 34 slow = slow->next; 35 } else { 36 runner->next = fast; 37 fast = fast->next; 38 } 39 runner = runner->next; 40 } 41 return result->next; 42 } 43 };
浙公网安备 33010602011771号