-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
83 lines (66 loc) · 1.21 KB
/
Copy pathmain.cpp
File metadata and controls
83 lines (66 loc) · 1.21 KB
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
// O(nlog(n))śÔÁ´ąí˝řĐĐĹĹĐň
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
ListNode *Merge(ListNode *left, ListNode *right)
{
ListNode dummy(0);
ListNode *tmp = &dummy;
while (left && right)
{
if (left->val < right->val)
{
tmp->next = left;
left = left->next;
}
else
{
tmp->next = right;
right = right->next;
}
tmp = tmp->next;
}
if (left)
tmp->next = left;
if (right)
tmp->next = right;
return dummy.next;
}
ListNode *SortList(ListNode *head)
{
if (!head || !head->next)
return head;
ListNode *p = head, *q = head->next;
while (q && q->next)
{
p = p->next;
q = q->next->next;
}
ListNode *left = SortList(p->next);
p->next = nullptr;
ListNode *right = SortList(head);
return Merge(left, right);
}
int main()
{
ListNode *l1 = new ListNode(3);
ListNode *l2 = new ListNode(2);
ListNode *l3 = new ListNode(6);
ListNode *l4 = new ListNode(4);
ListNode *l5 = new ListNode(5);
ListNode *l6 = new ListNode(9);
ListNode *l7 = new ListNode(7);
ListNode *l8 = new ListNode(8);
l1->next = l2;
l2->next = l3;
l3->next = l4;
l4->next = l5;
l5->next = l6;
l6->next = l7;
l7->next = l8;
SortList(l1);
return 0;
}