recursive mergesort
/**
* 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;
}
};