归并
/**
* 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) {
return mergeSort(head);
}
ListNode* mergeSort(ListNode* node){
if(!node||!node->next)
return node;
ListNode* fast=node;
ListNode* slow=node;
ListNode* mid=node;
while(fast && fast->next){
fast=fast->next->next;
mid = slow;
slow=slow->next;
}
mid->next=nullptr;
ListNode* l1=mergeSort(node);
ListNode* l2=mergeSort(slow);
return merge(l1,l2);
}
ListNode* merge(ListNode* l1,ListNode* l2){
ListNode* Head = new ListNode(-1);
ListNode* rear = Head;
while(l1 && l2){
if(l1->val<l2->val){
rear->next=l1;
rear=rear->next;
l1=l1->next;
}
else{
rear->next=l2;
rear=rear->next;
l2=l2->next;
}
}
if(l1)
rear->next=l1;
if(l2)
rear->next=l2;
return Head->next;
}
};