Created
December 26, 2018 04:29
-
-
Save kanrourou/a661ecd800c0e8ebdfc35a84567aa5ea to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 mergeSort(head); | |
} | |
private: | |
ListNode* mergeSort(ListNode* head) | |
{ | |
if(!head || !head->next)return head; | |
//partition | |
auto fast = head, slow = head; | |
while(fast->next && fast->next->next) | |
{ | |
fast = fast->next->next; | |
slow = slow->next; | |
} | |
auto head2 = slow->next; | |
slow->next = nullptr; | |
auto curr1 = mergeSort(head), curr2 = mergeSort(head2); | |
//merge | |
ListNode* newHead = curr1->val <= curr2->val? curr1: curr2, *curr = newHead; | |
if(curr == curr1)curr1 = curr1->next; | |
else curr2 = curr2->next; | |
while(curr1 && curr2) | |
{ | |
if(curr1->val <= curr2->val) | |
{ | |
curr->next = curr1; | |
curr = curr->next; | |
curr1 = curr1->next; | |
} | |
else | |
{ | |
curr->next = curr2; | |
curr = curr->next; | |
curr2 = curr2->next; | |
} | |
} | |
if(curr1)curr->next = curr1; | |
if(curr2)curr->next = curr2; | |
return newHead; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment