Sort a linked list in O(n log n) time using constant space complexity.
//采用归并排序
class Solution {
public:
ListNode* findMinddle(ListNode* head){
ListNode* slowPointer = head;
ListNode* fastPointer = head->next;
while(fastPointer != NULL &&
fastPointer->next != NULL) {
fastPointer = fastPointer->next->next;
slowPointer = slowPointer->next;
}
return slowPointer;
}
ListNode* mergeSort(ListNode* left, ListNode* right) {
if(!left)return right;
if(!right)return left;
ListNode* dummy = new ListNode(0);
ListNode* head = dummy;
while(left!=NULL && right!= NULL){
if(left->val < right->val){
head->next = left;
left = left->next;
}
else{
head->next = right;
right = right->next;
}
head = head->next;
}
while(left!=NULL){
head->next = left;
left = left->next;
head = head->next;
}
while(right!=NULL){
head->next = right;
right = right->next;
head = head->next;
}
return dummy->next;
}
ListNode* sortList(ListNode *head) {
if(!head || !head->next)return head;
ListNode* minddle = findMinddle(head);
ListNode* right = sortList(minddle->next);
minddle->next = NULL;
ListNode* left = sortList(head);
return mergeSort(left,right);
}
};