/**
* 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||!head->next) return head;
ListNode * slow = head;
ListNode * fast = head;
ListNode * pre = head;
while(fast && fast->next){
pre = slow;
slow = slow->next;
fast = fast->next->next;
}
pre->next =NULL;
return mergeList(sortList(head),sortList(slow));//合并有序的两个链表
}
ListNode * mergeList(ListNode* p1,ListNode * p2){
if(!p1) return p2;
if(!p2) return p1;
if(p1->val < p2->val){
p1->next = mergeList(p1->next,p2);
return p1;
}else{
p2->next = mergeList(p1,p2->next);
return p2;
}
}
};