-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreorderList.cpp
More file actions
35 lines (32 loc) · 943 Bytes
/
reorderList.cpp
File metadata and controls
35 lines (32 loc) · 943 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
class Solution {
public:
void reorderList(ListNode* head) {
if (!head || !head->next) {
return;
}
// Find the middle node of the list
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
// Reverse the second half of the list
ListNode *prev = nullptr, *curr = slow->next;
slow->next = nullptr;
while (curr) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
// Merge the two halves of the list
ListNode *p1 = head, *p2 = prev;
while (p1 && p2) {
ListNode *next1 = p1->next, *next2 = p2->next;
p1->next = p2;
p2->next = next1;
p1 = next1;
p2 = next2;
}
}
};