-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path143_reorder_list.cpp
More file actions
43 lines (34 loc) · 961 Bytes
/
143_reorder_list.cpp
File metadata and controls
43 lines (34 loc) · 961 Bytes
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
#include <cstddef>
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) {
return;
}
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode* second = slow->next;
slow->next = nullptr;
ListNode* prev = nullptr;
while (second) {
ListNode* next_node = second->next;
second->next = prev;
prev = second;
second = next_node;
}
ListNode* first = head;
second = prev;
while (second) {
ListNode* next_first = first->next;
ListNode* next_second = second->next;
first->next = second;
second->next = next_first;
first = next_first;
second = next_second;
}
}
};