-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReorder-list.cc
43 lines (42 loc) · 1.07 KB
/
Reorder-list.cc
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode *head) {
if(head == nullptr || head->next == nullptr) return;
ListNode *fast(head->next), *slow(head);
while(fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
ListNode *rhs = slow->next;
slow->next = nullptr;
rhs = reverse(rhs);
//merge head and lhs
ListNode *next(nullptr);
while(rhs) {
next = rhs->next;
rhs->next = head->next;
head->next = rhs;
head = head->next->next;
rhs = next;
}
}
private:
ListNode *reverse(ListNode *list) {
ListNode *new_list(nullptr), *next(nullptr);
while(list) {
next = list->next;
list->next = new_list;
new_list = list;
list = next;
}
return new_list;
}
};