-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorder_List.cpp
More file actions
49 lines (40 loc) · 1.2 KB
/
Reorder_List.cpp
File metadata and controls
49 lines (40 loc) · 1.2 KB
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
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
#include <stack>
class Solution {
public:
void reorderList(ListNode* head) {
if (head->next == nullptr || head->next->next == nullptr) {
return;
}
std::stack<ListNode*> stck;
// Traverse the list and put them into a stack
ListNode* p = head->next;
while (p != nullptr) {
stck.push(p);
p = p->next;
}
int size = stck.size();
ListNode* saveHead = head;
// Only the top half of the stack will be re-inserted into the list
size = size % 2 == 0 ? size / 2: size / 2 + 1;
// Re-insert top half of the stack at every other node
for (int i=0; i<size; i++) {
p = stck.top();
stck.pop();
ListNode* temp = head->next;
head->next = p;
p->next = temp;
head = temp;
}
// Set new tail
head->next = nullptr;
head = saveHead;
}
};