AcWing 1451. 单链表快速排序
宋标 Lv5

题目

给定一个单链表,请使用快速排序算法对其排序。

要求:期望平均时间复杂度为 ,期望额外空间复杂度为

思考题: 如果只能改变链表结构,不能修改每个节点的val值该如何做呢?

数据范围

链表中的所有数大小均在 范围内,链表长度在
本题数据完全随机生成。

输入样例:

[5, 3, 2]

输出样例:

[2, 3, 5]

题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:

ListNode* get_tail(ListNode* head){
while (head -> next) head = head -> next;
return head;
}

ListNode* quickSortList(ListNode* head) {

if (!head || !head -> next) return head;

auto left = new ListNode(-1), mid = new ListNode(-1), right = new ListNode(-1);
auto ltail = left, mtail = mid, rtail = right;
int val = head -> val;

for (auto p = head; p; p = p -> next)
{
int pv = p -> val;
if (pv < val) ltail = ltail -> next = p;
else if (val == pv) mtail = mtail -> next = p;
else rtail = rtail -> next = p;
}

ltail -> next = mtail -> next = rtail -> next = NULL;
left -> next = quickSortList(left -> next);
right -> next = quickSortList(right -> next);

get_tail(left) -> next = mid -> next;
get_tail(mid) -> next = right -> next;

return left -> next;
}
};
 评论