-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy pathkReverse VishalRastogi.cpp
144 lines (119 loc) · 2.64 KB
/
kReverse VishalRastogi.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
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include<bits/stdc++.h>
using namespace std;
struct node
{
int data;
node * next;
node(int data)
{
this->data = data;
next = NULL;
}
};
void create(node * &head,int n)
{
if(n==0)
{
head = NULL;
return;
}
int data;
cin>>data;
head = new node(data);
node * trav = head;
n--;
while(n--)
{
//cout<<"***"<<endl;
int data;
cin>>data;
trav->next = new node(data);
trav = trav->next;
}
}
void print(node* &head)
{
// cout<<"print chla";
node * trav = head;
while(trav!=NULL)
{
cout<<trav->data<<" ";
trav = trav->next;
}
cout<<endl;
}
void display(node* head, node* tail)
{
//cout<<"Display chla"<<endl;
while(head!=tail)
{
cout<<head->data<<" ";
head = head->next;
}
cout<<head->data<<endl;
return;
}
pair <node*,node*> reve(pair<node*,node*> p,bool flag = false)
{
//cout<<"reverse chlr rha hai"<<endl;
node* head = p.first;
node * tail = p.second;
if(head == tail)
{
return make_pair(tail,head); // return pair of new link list if head and tail are same
}
//cout<<head->data<<" : "<<tail->data<<endl;
pair <node*,node*> nll = reve(make_pair(head->next,tail));
node* nhead = nll.first;
node* ntail = nll.second;
ntail->next = head; // linking new tail with old head head
if(flag)
{
ntail->next->next = NULL;
}
return make_pair(nhead,ntail->next); //returning new head and
}
node* Kreverse(node * head,int k)
{
//cout<<"Kreverse chla with head = "<<head->data<<endl;
node * tail = head;
int it = k;
while(--it)
{
//cout<<"value of it"<<it<<endl;
//cout<<"value of tailnext"<<tail->next<<endl;
if(tail->next!=NULL)
{
tail = tail->next;
}
}
if(tail->next==NULL)
{
//cout<<"NULLaa hogya"<<endl;
// display(head,tail);
pair <node*,node*> ll = reve(make_pair(head,tail),true);
//print(ll.first);
//cout<<"he is back"<<ll.first<<endl;
return ll.first;
}
//display(head,tail);
node * prev_ll_head = Kreverse(tail->next,k);
pair <node*,node*> curr_ll = reve(make_pair(head,tail),true);
//display(curr_ll.first,curr_ll.second);
node * curr_ll_tail = curr_ll.second;
(curr_ll_tail)->next = prev_ll_head;
//print(curr_ll.first);
return curr_ll.first;
}
int main()
{
int n,k;
cin>>n>>k;
node * head;
create(head,n);
//cout<<"input hogya"<<endl;
//print(head);
node * new_head = Kreverse(head,k);
//cout<<"katm hogya"<<endl;
print(new_head);
}