此处,先放置几个常见的排序算法的时间及空间复杂度,链接如下:https://blog.csdn.net/qq_40467670/article/details/122769460。由于题目要求,这里选择归并排序,满足它的复杂度要求。
题目链接:https://leetcode-cn.com/problems/sort-list/
题目如下:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* sortList(ListNode* head) {
//自顶向下归并
return sortList(head,nullptr);
}
ListNode* sortList(ListNode* head,ListNode* tail){
if(head==nullptr) return head;
if(head->next==tail){
head->next=nullptr;
return head;
}
//找到链表的中点slow
ListNode* slow=head,*fast=head;
while(fast!=tail){
slow=slow->next;
fast=fast->next;
if(fast!=tail){
fast=fast->next;
}
}
ListNode* mid=slow;
//拆分成两个子链表,并对两个子链表分别递归,合并排序
return merge(sortList(head,slow),sortList(slow,tail));
}
ListNode* merge(ListNode* l1,ListNode* l2){
ListNode* result=new ListNode(-1);
ListNode* p=result;
while(l1&&l2){
if(l1->val<l2->val){
p->next=l1;
l1=l1->next;
}else {
p->next=l2;
l2=l2->next;
}
p=p->next;
}
if(l1) p->next=l1;
if(l2) p->next=l2;
return result->next;
}
};