2021年04月18日 周日 天气晴 【不悲叹过去,不荒废现在,不惧怕未来】
1. 题目简介
2. 题解
2.1 快速排序
2.1.1 值交换
(1)递归
整体过程和数组的快排很相似,但要注意的是:tail为最后一个需要排序元素的下一个位置。
class Solution {
public:
ListNode* sortList(ListNode* head) {
quickSort(head,nullptr);
return head;
}
void quickSort(ListNode* head, ListNode* tail){
// tail为最后一个需要排序元素的下一个位置
if(head==tail || head->next==tail) return;
int pivot = head->val;
ListNode* left = head, *cur = head->next;
// 核心操作:将小于pivot的交换到其左边,大于pivot的交换到其右边
while(cur != tail){
if(cur->val < pivot){
left = left->next;
swap(left->val, cur->val);
}
cur = cur->next;
}
swap(head->val, left->val);
quickSort(head,left);
quickSort(left->next,tail);
}
};
(2)迭代
利用栈可以将递归改写成迭代。
class Solution {
public:
ListNode* sortList(ListNode* head) {
stack<ListNode*> stk;
stk.push(nullptr);
stk.push(head);
ListNode* l = nullptr, *r = nullptr;
ListNode* tmp = nullptr;
while(!stk.empty()){
// r为最后一个需要排序元素的下一个位置
l = stk.top(); stk.pop();