/**
* 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) {
if(head == nullptr || head->next == nullptr) return head;
ListNode *fast(head), *slow(head);
while(fast->next && fast->next->next){
fast = fast->next->next;
slow = slow->next;
}
fast = slow;
slow = slow->next;
fast->next = nullptr;
ListNode *l1 = sortList(head);
ListNode *l2 = sortList(slow);
return merge2Lists(l1, l2);
}
ListNode* merge2Lists(ListNode *l1, ListNode *l2){
if(l1 == nullptr) return l2;
if(l2 == nullptr) return l1;
ListNode node(-1);
ListNode *p(&node);
while(l1 && l2){
if(l1->val < l2 -> val){
p->next = l1;
l1 = l1->next;
}
else{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1) p->next = l1;
else if(l2) p->next = l2;
return node.next;
}
};