forked from codedecks-in/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
143.Reorder_List.cpp
45 lines (38 loc) · 1.07 KB
/
143.Reorder_List.cpp
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
/* medium difficulty */
class Solution {
public:
void reorderList(ListNode* head) {
//edge cases
if ((!head) || (!head->next) || (!head->next->next)) return;
int l=0; //to calculate the length
ListNode* curr=head;
while(curr){
l++;
curr=curr->next;
}
//stack to store the second half of the elements of the ll
stack<ListNode*> s;
curr=head;
//iterating till the end of the first half
int m=(l+1)/2;
while(m>=1){
curr=curr->next;
m--;
}
//pushing the second half of the elements in the stack
while(curr){
s.push(curr);
curr=curr->next;
}
//attaching the elements from the top of the stack to the first half of the elements
curr=head;
while(curr&&!s.empty()){
ListNode* temp=s.top();
s.pop();
temp->next=curr->next;
curr->next=temp;
curr=curr->next->next;
}
curr->next=NULL;
}
};