链表排序,要求使用 O(nlgn) 时间,常量空间。
使用归并的思路
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *findMid(ListNode *head) { ListNode *mid; ListNode *fast = head->next; ListNode *slow = head; while(fast && fast->next) { fast = fast->next; fast = fast->next; slow = slow->next; } mid = slow; return mid; } ListNode *sortList(ListNode *head) { if(head == NULL || head->next == NULL) return head; ListNode *tmp = findMid(head); ListNode *right = sortList(tmp->next); tmp->next = NULL; ListNode *left = sortList(head); ListNode *newHead = new ListNode(-1); newHead->next = merge(left,right); return newHead->next; } ListNode *merge(ListNode *left, ListNode *right) { ListNode *dummy = new ListNode(-1); for(ListNode *p = dummy; left!=NULL || right!= NULL; p = p->next) { int leftVal = left == NULL? INT_MAX:left->val; int rightVal = right == NULL?INT_MAX:right->val; if(leftVal <= rightVal) { p->next = left; left = left->next; } else { p->next = right; right = right->next; } } return dummy->next; } };