題目描述:
思路1:遍歷鏈表並記錄數據,然後將數據採用sort()排序(時間複雜度O(logn)),然後從頭到尾把排好序的元素更新到鏈表中
/**
* 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==NULL)
return head;
vector<int> sortVec;
ListNode* p=head;
while(p){
sortVec.push_back(p->val);
p=p->next;
}
sort(sortVec.begin(),sortVec.end());
p=head;
int i=0;
while(p){
p->val=sortVec[i++];
p=p->next;
}
return head;
}
};
思路2:歸併排序
/**
* 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==NULL||head->next==NULL)//空鏈表||只有一個節點的鏈表
return head;
return merge(head);
}
ListNode* merge(ListNode* &head){
if(head==NULL||head->next==NULL)
return head;
ListNode *fast, *slow;//使用快慢指針將鏈表均分
ListNode *pre;
fast=slow=head;
while(fast){
pre=slow;
slow=slow->next;
fast=fast->next;
if(fast)//在移動快指針的時候需要注意第二次移動的方式
fast=fast->next;
}
pre->next=NULL;
ListNode *l,*r;
l=merge(head);
r=merge(slow);
return mergeSort(l,r);
}
ListNode* mergeSort(ListNode* &l,ListNode* &r){
//這種創建新鏈表的方法需要學會,先創建一個頭結點,最後再將這個頭結點刪除
ListNode* pRes=new ListNode(0);
ListNode* p=pRes;
while(l&&r){
if(l->val<=r->val){
p->next=l;
l=l->next;
}else{
p->next=r;
r=r->next;
}
p=p->next;
}
if(l)
p->next=l;
if(r)
p->next=r;
p=pRes->next;
delete pRes;
return p;
}
};