-
Notifications
You must be signed in to change notification settings - Fork 0
/
L46-1.cpp
48 lines (39 loc) · 1017 Bytes
/
L46-1.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
// Reverse in k group
/****************************************************************
Following is the Linked List node structure
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
Node* kReverse(Node* head, int k) {
//base call
if(head == NULL) {
return NULL;
}
//step1: reverse first k nodes
Node* next = NULL;
Node* curr = head;
Node* prev = NULL;
int count= 0;
while( curr != NULL && count < k ) {
next = curr -> next;
curr -> next = prev;
prev = curr;
curr = next;
count++;
}
//step2: Recursion dekhlega aage ka
if(next != NULL) {
head -> next = kReverse(next,k);
}
//step3: return head of reversed list
return prev;
}