-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path143.cpp
More file actions
37 lines (36 loc) · 1017 Bytes
/
Copy path143.cpp
File metadata and controls
37 lines (36 loc) · 1017 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
class Solution {
public:
void reorderList(ListNode *head) {
if (!head || !head->next || !head->next->next)
return;
ListNode *slow = head, *fast = head, *start = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
ListNode *temp = slow;
slow = slow->next;
temp->next = nullptr;
slow = reverseListNode(slow);
while (slow) {
ListNode *tempA = start->next, *tempB = slow->next;
start->next = slow;
slow->next = tempA;
start = tempA;
slow = tempB;
}
}
ListNode *reverseListNode(ListNode *head) {
if (!head->next)
return head;
ListNode *prev = head->next, *temp = nullptr;
head->next = nullptr;
while (prev) {
temp = prev->next;
prev->next = head;
head = prev;
prev = temp;
}
return head;
}
};