思路:
使用归并排序实现,时间复杂度为O(nlogn),空间负责为常数阶**O(n)**的算法
代码步骤:
- 一个用于链表中心查找,进行链表的递归分割;
- 一个用于对两个链表的合并,创建新表头,按序挑选元素;
代码实现:
class Solution {
public:
ListNode* sortList(ListNode* head, ListNode* tail) {
//链表为空
if (head == nullptr)
return head;
//链表只有一个元素——递归终止条件
if (head->next == tail) {
head->next = nullptr;
return head;
}
//利用双指针(快慢指针)查找链表中点
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, mid), sortList(mid, tail));
}
ListNode* merge(ListNode* head1, ListNode* head2) {
//创建一个新表头
ListNode* Head_front = new ListNode(0);
ListNode* temp = Head_front, *temp1 = head1, *temp2 = head2;
//对比两个链表之间的值
while (temp1 != nullptr && temp2 != nullptr) {
if (temp1->val <= temp2->val) {
temp->next = temp1;
temp1 = temp1->next;
}
else {
temp->next = temp2;
temp2 = temp2->next;
}
temp = temp->next;
}
//将剩余数据进行一次拼接
temp->next=temp1==nullptr? temp2:temp1;
return Head_front->next;
}
};