Created
April 2, 2017 09:13
-
-
Save s4553711/8168980bda327738d7ba65097f7e5ebc to your computer and use it in GitHub Desktop.
recursive mergesort
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) { | |
ListNode *p1, *p2, *front, *back; | |
p1 = head; | |
p2 = head; | |
if (head == NULL || head->next == NULL) return head; | |
else { | |
while (p1->next != NULL && p1->next->next != NULL) { | |
p1 = p1->next->next; | |
p2 = p2->next; | |
} | |
} | |
p1 = p2; | |
p2 = p2->next; | |
p1->next = NULL; | |
front = sortList(head); | |
back = sortList(p2); | |
return merge(front, back); | |
} | |
ListNode* merge(ListNode* h1, ListNode*h2) { | |
ListNode *res, *p; | |
if (h1 == NULL) return h2; | |
if (h2 == NULL) return h1; | |
if (h1->val < h2->val) { | |
res = h1; | |
h1 = h1->next; | |
} else { | |
res = h2; | |
h2 = h2->next; | |
} | |
p = res; | |
while (h1 != NULL && h2 != NULL) { | |
if (h1->val < h2->val) { | |
p->next = h1; | |
h1 = h1->next; | |
} else { | |
p->next = h2; | |
h2 = h2->next; | |
} | |
p = p->next; | |
} | |
if (h1 != NULL) p->next = h1; | |
else if (h2 != NULL) p->next = h2; | |
return res; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment