思路:用歸并排序。對一個連結清單采用遞歸進行二等分,直到每個部分有序,然後對其進行合并。其實就是兩步,先分解,然後合并有序連結清單。
代碼:
//對連結清單采用遞歸排序
class Solution {
public:
ListNode* sortList(ListNode* head){
if(head==NULL||head->next==NULL)
return head;
return mergeSort(head);
}
ListNode* mergeSort(ListNode* head){
//遞歸終止條件
if(head==NULL||head->next==NULL)
return head;
ListNode* p=head;ListNode* q=head;ListNode* prep=NULL;
while (q!=NULL&&q->next!=NULL)
{
q=q->next->next;
prep=p;
p=p->next;
}
prep->next=NULL;//對連結清單進行切分
ListNode* lhalf=mergeSort(head);
ListNode* rhalf=mergeSort(p);
ListNode* res=merge(lhalf,rhalf);
return res;
}
//合并兩個有序連結清單
ListNode* merge(ListNode* lh,ListNode* rh){
ListNode* tempHead=new ListNode(0);
ListNode* p=tempHead;
while (lh&&rh)
{
if(lh->val<=rh->val){
p->next=lh;
lh=lh->next;
}else{
p->next=rh;
rh=rh->next;
}
p=p->next;
}
if(lh==NULL)
p->next=rh;
else
p->next=lh;
p=tempHead->next;
tempHead->next=NULL;
delete tempHead;
return p;
}
};
轉載于:https://www.cnblogs.com/fightformylife/p/4379408.html