采用归并排序:
/**
* 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 *head){
if(head==NULL||head->next==NULL) return head;
ListNode *p=head;
ListNode *q=head;
ListNode *pre=p;
while(q!=NULL&&q->next!=NULL){
pre=p;
p=p->next;
q=q->next->next;
}
pre->next=NULL;
ListNode *h1=mergeSort(head);
ListNode *h2=mergeSort(p);
merge(h1,h2);
}
ListNode *merge(ListNode *h1,ListNode *h2){
ListNode *dump=new ListNode(0);
ListNode *p=dump;
while(h1!=NULL && h2!=NULL){
if(h1->val<h2->val){
p->next=h1;
h1=h1->next;
}else{
p->next=h2;
h2=h2->next;
}
p=p->next;
}
if(h1!=NULL) {
p->next=h1;
}else{
p->next=h2;
}
ListNode* head=dump->next;
delete dump;
return head;
}
};