在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
采用归并排序,将数组换成链表即可
/**
* 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==nullptr)
return nullptr;
ListNode* cur=head;
int i=0;//链表的长度
while(cur!=nullptr)
{
cur=cur->next;
i++;
}
return sort(head,0,i-1);
}
ListNode* sort(ListNode* head,int l,int r){
if(l>=r)
return head;
int mid=l+(r-l)/2;
ListNode* cur=head;
int i=0;
while(cur!=nullptr&&i<mid-l)//找到中点所在位置
{
cur=cur->next;
i++;
}
ListNode* tmp=cur->next;
cur->next=nullptr;//断开
ListNode* left=sort(head,l,mid);
ListNode* right=sort(tmp,mid+1,r);
ListNode* res=merge(left,right);
return res;
}
ListNode* merge(ListNode* a,ListNode* b){
ListNode* root=new ListNode(0);
ListNode* cur=root;
while(a!=nullptr||b!=nullptr)
{
if(a==nullptr)
{
cur->next=b;
break;
}
else if(b==nullptr)
{
cur->next=a;
break;
}
else if(a->val<b->val)
{
cur->next=new ListNode(a->val);
cur=cur->next;
a=a->next;
}
else
{
cur->next=new ListNode(b->val);
cur=cur->next;
b=b->next;
}
}
return root->next;
}
};