-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreorderList.cpp
101 lines (79 loc) · 1.72 KB
/
reorderList.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
//O(n^2)时间复杂度
void reorderList(ListNode *head)
{
if (head == NULL)
return;
ListNode *cur, *end, *end_prev;
cur = head;
while (cur->next && cur->next->next) {
end_prev = cur;
while (end_prev->next->next)
end_prev = end_prev->next;
end = end_prev->next;
end_prev->next = NULL;
end->next = cur->next;
cur->next = end;
cur = end->next;
}
return;
}
//O(n)时间复杂度
//反转链表
ListNode* reverseList(ListNode *head)
{
if (!head || !head->next)
return head;
ListNode *prev, *cur, *next;
prev = head;
cur = head->next;
while (cur) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
head->next = NULL;
return prev;
}
void mergeList(ListNode *first, ListNode *second)
{
ListNode *fcur, *fnext, *scur, *snext;
fcur = first, scur = second;
while (fcur && scur) {
fnext = fcur->next;
snext = scur->next;
fcur->next = scur;
scur->next = fnext;
fcur = fnext;
scur = snext;
}
}
void reorderList(ListNode *head)
{
if (!head || !head->next || !head->next->next)
return;
int cnt;
ListNode *head1, *head2;
cnt = 0;
head1 = head;
while (head1) {
cnt++;
head1 = head1->next;
}
if (cnt % 2 == 0) {
cnt = cnt / 2;
} else {
cnt = cnt / 2 + 1;
}
head2 = head;
while (--cnt) {
head2 = head2->next;
}
head1 = head2;
head2 = head2->next;
head1->next = NULL;
head1 = head;
head2 = reverseList(head2);
mergeList(head1, head2);
return;
}