-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathreverseKgrpLinkedList.cpp
86 lines (67 loc) · 1.27 KB
/
reverseKgrpLinkedList.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
#include <iostream>
using namespace std ;
class Node{
public:
int data;
Node* next;
// CONSTRUCTOR
Node(int data){
this -> data = data ;
this -> next = NULL;
}
};
void insertAtHead( Node* &head,int data){
Node* New = new Node(data);
New -> next = head ;
head = New ;
};
void print(Node* head){
Node* New = head ;
while (New != NULL)
{
cout << New -> data << " ";
New = New -> next ;
}
cout << endl ;
};
Node* reversekGroup(Node* head,int k){
if (head == NULL )
{
return NULL ;
}
Node* forward = NULL ;
Node* prev = NULL ;
Node* current = head ;
int count = 0;
while (current != NULL && count < k)
{
forward = current -> next ;
current -> next = prev ;
prev = current ;
current = forward ;
count++;
}
if (forward != NULL )
{
head -> next = reversekGroup(forward,k);
}
return prev ;
};
int main(){
Node* head = NULL ;
insertAtHead(head,10);
print(head);
insertAtHead(head,20);
print(head);
insertAtHead(head,30);
print(head);
insertAtHead(head,40);
print(head);
insertAtHead(head,50);
print(head);
cout << " REVERSE "<<endl;
int k; cin >> k ;
head = reversekGroup(head,k);
print(head);
return 0;
}