class
Solution {
public :
ListNode *sortList(ListNode *head) {
if
(head == NULL || head->next == NULL)
return
head;
ListNode *slow = head, *fast = head;
while
(fast->next != NULL && fast->next->next != NULL) {
fast = fast->next->next;
slow = slow->next;
}
fast = slow;
slow = slow->next;
fast->next = NULL;
fast = sortList(head);
slow = sortList(slow);
return
merge(fast, slow);
}
ListNode *merge(ListNode *first, ListNode *second) {
if
(first == NULL) return
second;
if
(second == NULL) return
first;
ListNode *ret, *p;
if
(first->val < second->val) {
ret = first;
first = first->next;
} else
{
ret = second;
second = second->next;
}
p = ret;
while
(first != NULL && second != NULL) {
if
(first->val <second->val) {
p->next = first;
first = first->next;
} else
{
p->next = second;
second = second->next;
}
p = p->next;
}
if
(first != NULL) p->next = first;
else
if (second != NULL) p->next = second;
return
ret;
}
};
|