时间轴

2025-12-01

init


题目:

归并排序:

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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 {
private:
ListNode *mergeSort(ListNode *head)
{
if (head == nullptr || head->next == nullptr) {
return head;
}

// 归并排序
ListNode *low, *fast;
low = head;
fast = head->next;
// find middle
while (fast != nullptr && fast->next != nullptr) {
low = low->next;
fast = fast->next->next;
}
ListNode *h2_head = low->next;
low->next = nullptr;
//now low is middle
ListNode *h1 = mergeSort(head); // head ... low
ListNode *h2 = mergeSort(h2_head); // low .. tail

// merge
ListNode dummy;
ListNode *tail = &dummy, *tmp;
while (h1 || h2) {
if ((h1 && h2 && h1->val < h2->val) || (h1 && !h2)) {
tail->next = h1;
tail = h1;
h1 = h1->next;
tail->next = nullptr;

} else if ((h1 && h2 && h1->val >= h2->val) || (!h1 && h2)) {
tail->next = h2;
tail = h2;
h2 = h2->next;
tail->next = nullptr;
}
}

return dummy.next;
}

public:
ListNode *sortList(ListNode *head)
{
return mergeSort(head);
}
};