方法一:归并排序
/**
* 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) {
//cut
if(head==NULL || head->next==NULL) //如果链表为空或只有一个节点直接返回
return head;
ListNode* slow=head;
ListNode* fast=head->next;
while(fast!=NULL && fast->next!=NULL){ //快慢指针将链表分为两部分
slow=slow->next;
fast=fast->next->next;
}
ListNode *tmp=slow->next;
slow->next=NULL; //将第一部分切断
ListNode* left=sortList(head); //递归切断
ListNode* right=sortList(tmp);
//merge
ListNode* res =new ListNode(-1);
ListNode* h=res;
while(left!=NULL && right!=NULL){ //两个链表合并
if(left->val < right->val){
h->next=left;
left=left->next;
}
else{
h->next=right;
right=right->next;
}
h=h->next;
}
h->next=left?left:right;
return res->next;
}
};