-
Notifications
You must be signed in to change notification settings - Fork 368
/
Reverse in group of K.cpp
81 lines (71 loc) · 1.45 KB
/
Reverse in group of K.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
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
//constructor to initialise value
Node(int x){
data=x;
next=NULL;
}
};
Node *Insert(Node *head,int val){
Node *temp=new Node(val);
if(head==NULL){
temp->next=head;
return temp;
}
Node *curr=head;
while(curr->next != NULL)
curr=curr->next;
curr->next=temp;
temp->next=NULL;
return head;
}
Node *reverseinK(Node *head,int k){
Node *curr=head,*prevFirst=NULL;
bool isFirstPass=true;
while(curr!=NULL){
Node *first=curr,*prev=NULL;
int count=0;
while(curr!=NULL && count<k){
Node *next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
count++;
}
if(isFirstPass){
head=prev;
isFirstPass=false;
}
else
prevFirst->next=prev;
prevFirst=first;
}
return head;
}
void print(Node *head){
Node *curr=head;
cout<<endl<<endl;
while(curr != NULL){
cout<<curr->data<<"->";
curr=curr->next;
}
cout<<"NULL"<<endl<<endl;
}
int main(){
Node *head=NULL;
int n,val,k;
cout<<"Enter n, k : ";
cin>>n>>k;
cout<<"Enter nodes : \n";
for(int i=0; i<n; i++){
cin >> val;
head=Insert(head,val);
}
print(head);
head=reverseinK(head,k);
print(head);
return 0;
}