-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy path27 May Modify Linked List-1
84 lines (73 loc) · 1.72 KB
/
27 May Modify Linked List-1
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
class Solution{
public:
Node* reverse(Node* node) {
Node* prev= NULL;
Node* curr = node;
while(curr){
Node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
struct Node* modifyTheList(struct Node *head)
{
Node* node = head;
int cnt = 0;
while(node){
cnt++;
node =node->next;
}
Node* slow = head;
Node* fast = head;
Node* prev;
while(fast && fast->next) {
prev = slow;
slow = slow->next;
fast= fast->next->next;
}
if(cnt%2){
Node* helper = reverse(slow->next);
slow->next = helper;
}
else{
Node* helper = reverse(slow);
prev->next = helper;
}
slow = head;
fast = head;
while(fast && fast->next)
{
slow = slow->next;
fast = fast->next->next;
}
fast = head;
if(cnt%2)
slow = slow->next;
while(slow){
int val = fast->data;
fast->data = slow->data-val;
slow->data = val;
slow = slow->next;
fast = fast->next;
}
slow = head;
fast = head;
prev = NULL;
while(fast && fast->next) {
prev = slow;
slow = slow->next;
fast= fast->next->next;
}
if(cnt%2){
Node* helper2 = reverse(slow->next);
slow->next = helper2;
}
else{
Node* helper2 = reverse(slow);
prev->next = helper2;
}
return head;
}
};