forked from Thelalitagarwal/GFG_Daily_Problem
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReorder List.cpp
More file actions
50 lines (47 loc) · 1.14 KB
/
Reorder List.cpp
File metadata and controls
50 lines (47 loc) · 1.14 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
50
class Solution{
private:
Node* reverse(Node* head){
Node* curr=head;
Node* prev=NULL;
Node* temp=NULL;
while(curr!=NULL){
temp=curr->next;
curr->next=prev;
prev=curr;
curr=temp;
}
return prev;
}
Node* getmid(Node* head){
Node* slow = head;
Node* fast = head->next;
while(fast!=NULL && fast->next!=NULL){
slow=slow->next;
fast=fast->next->next;
}
return slow;
}
public:
void reorderList(Node* head) {
Node* l1 = head;
Node* mid = getmid(head);
Node* l2 = mid->next;
mid->next=NULL;
l2 = reverse(l2);
Node* ans=new Node(-1);
Node* curr=ans;
while(l1 || l2){
if(l1){
curr->next=l1;
curr=curr->next;
l1=l1->next;
}
if(l2){
curr->next=l2;
curr=curr->next;
l2=l2->next;
}
}
head = ans->next;
}
};