-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path143. Reorder List
59 lines (49 loc) · 1.24 KB
/
143. Reorder List
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
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) {
return;
}
ListNode* middle = midNode(head);
ListNode* newHead = middle->next;
middle->next = nullptr;
newHead = reverseLinkedList(newHead);
ListNode* c1 = head;
ListNode* c2 = newHead;
ListNode* f1 = nullptr;
ListNode* f2 = nullptr;
while (c1 && c2) {
// Backup
f1 = c1->next;
f2 = c2->next;
// Linking
c1->next = c2;
c2->next = f1;
// Move
c1 = f1;
c2 = f2;
}
}
private:
ListNode* midNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* reverseLinkedList(ListNode* head) {
ListNode* prev = nullptr;
ListNode* curr = head;
ListNode* forw = nullptr;
while (curr) {
forw = curr->next;
curr->next = prev;
prev = curr;
curr = forw;
}
return prev;
}
};