-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200213-1.cpp
105 lines (99 loc) · 1.73 KB
/
200213-1.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
// https://leetcode-cn.com/problems/sort-list/
#include <cstdio>
#include <initializer_list>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* init(initializer_list<int> a) {
ListNode node(0);
ListNode* p = &node;
for (auto e : a) {
p->next = new ListNode(e);
p = p->next;
}
return node.next;
}
void release(ListNode* p) {
if (p) release(p->next);
delete p;
}
void print(ListNode* p) {
printf("[ "); for (; p; p = p->next) printf("%d ", p->val); printf("]\n");
}
class Solution {
public:
ListNode* sortList(ListNode* head) {
if (!head || !head->next) return head;
int n = 0;
for (ListNode* p = head; p; p = p->next) ++n;
ListNode* p = head;
for (int i = 0; i + 1 < n / 2; ++i) p = p->next;
ListNode* q = p->next;
p->next = NULL;
p = head;
p = sortList(p);
q = sortList(q);
ListNode node(0);
ListNode* curr = &node;
for (;;) {
if (p && q) {
if (p->val <= q->val) {
curr->next = p;
p = p->next;
curr = curr->next;
} else {
curr->next = q;
q = q->next;
curr = curr->next;
}
} else if (p) {
curr->next = p;
p = p->next;
curr = curr->next;
} else if (q) {
curr->next = q;
q = q->next;
curr = curr->next;
} else {
break;
}
}
return node.next;
}
};
int main()
{
Solution s;
{
ListNode* p = init({4,2,1,3});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({-1,5,3,4,0});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
{
ListNode* p = init({1});
print(p);
p = s.sortList(p);
print(p);
release(p);
}
return 0;
}