-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question43.cpp
42 lines (40 loc) · 1012 Bytes
/
Question43.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 -> Reorder List
Solution :
class Solution {
public:
ListNode* reverse(ListNode*head){
ListNode*curr=head;
ListNode*forward=NULL;
ListNode*prev=NULL;
while(curr){
forward=curr->next;
curr->next=prev;
prev=curr;
curr=forward;
}
return prev;
}
void reorderList(ListNode* head) {
ListNode*slow=head;
ListNode*fast=head;
while(fast&&fast->next){
fast=fast->next->next;
slow=slow->next;
}
ListNode*newhead=slow->next;
slow->next=NULL;
newhead=reverse(newhead);
ListNode*curr1=head;
ListNode*curr2=newhead;
ListNode*forward1=NULL;
ListNode*forward2=NULL;
while(curr1&&curr2){
forward2=curr2->next;
forward1=curr1->next;
curr2->next=curr1->next;
curr1->next=curr2;
curr1=forward1;
curr2=forward2;
}
}
};