Sort a linked list in O(n log n) time using constant space complexity.
要求在O(nlgn)内完成链表排序。
对于单链表,可以使用归并排序。
其实我一开始想的是拍成数组然后直接排序再重建…
并且这个思路比较简单写起来也没什么难度
ListNode root(-1);
//拍成数组,O(n)
vector<int> arr;
ListNode* temp=head;
while(temp){
arr.push_back(temp->val);
temp=temp->next;
}
//数组排序O(nlogN)
sort(arr.begin(),arr.end());
//重建链表
ListNode* cur=&root;
for(int i=0;i<arr.size();i++){
cur->next=new ListNode(arr[i]);
cur=cur->next;
}
return root.next;
正确的归并排序解法
class Solution {
public:
ListNode* sortList(ListNode* head) {
if(!head || !head->next) return head;
//寻找中间节点
ListNode* slow,*fast;
slow=fast=head;
while(fast->next && fast->next->next){
slow=slow->next;
fast=fast->next->next;
}
//断开两节点
fast=slow;
slow=slow->next;
fast->next=NULL;
ListNode* l1=sortList(head);
ListNode* l2=sortList(slow);
return mergeTwoLists(l1,l2);
}
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2){
ListNode root(-1);
ListNode* cur=&root;
while(l1 && l2){
if(l1->val < l2->val){
cur->next=l1;
cur=l1;
l1=l1->next;
}
else{
cur->next=l2;
cur=l2;
l2=l2->next;
}
}
cur->next=l1?l1:l2;
return root.next;
}
};