Skip to content

Commit 7d6ff24

Browse files
committed
Reorder List Solution
1 parent 4d0c3f9 commit 7d6ff24

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

reorder-list/PDKhan.cpp

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// space O(n)
2+
class Solution {
3+
public:
4+
void reorderList(ListNode* head) {
5+
ListNode* search = head->next;
6+
ListNode* tail = head;
7+
deque<ListNode*> q;
8+
9+
while(search){
10+
ListNode* next = search->next;
11+
12+
search->next = NULL;
13+
q.push_back(search);
14+
search = next;
15+
}
16+
17+
for(int i = 0; !q.empty(); i++){
18+
if(i % 2 == 0){
19+
tail->next = q.back();
20+
q.pop_back();
21+
}else{
22+
tail->next = q.front();
23+
q.pop_front();
24+
}
25+
26+
tail = tail->next;
27+
}
28+
}
29+
};
30+
31+
32+
// space O(1)
33+
class Solution {
34+
public:
35+
void reorderList(ListNode* head) {
36+
if(head == NULL || head->next == NULL)
37+
return;
38+
39+
ListNode* slow = head;
40+
ListNode* fast = head;
41+
42+
while(fast->next && fast->next->next){
43+
slow = slow->next;
44+
fast = fast->next->next;
45+
}
46+
47+
ListNode* prev = nullptr;
48+
ListNode* curr = slow->next;
49+
50+
while(curr){
51+
ListNode* next = curr->next;
52+
curr->next = prev;
53+
prev = curr;
54+
curr = next;
55+
}
56+
57+
slow->next = nullptr;
58+
59+
ListNode* first = head;
60+
ListNode* second = prev;
61+
62+
while(first && second){
63+
ListNode* next1 = first->next;
64+
ListNode* next2 = second->next;
65+
66+
first->next = second;
67+
second->next = next1;
68+
69+
first = next1;
70+
second = next2;
71+
}
72+
}
73+
};

0 commit comments

Comments
 (0)