-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path33-Reverse Nodes in k-Group
73 lines (55 loc) · 1.69 KB
/
33-Reverse Nodes in k-Group
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
#include <bits/stdc++.h>
/****************************************************************
Following is the class structure of the Node class:
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
*****************************************************************/
Node* getListAfterReverseOperation(Node *head, int n, int arr[]) {
if(head == NULL or head->next == NULL)
return head;
Node* dummy = new Node(0);
dummy->next = head;
Node* prevNode = dummy;
Node* currNode;
Node* nextNode;
for(int index=0; index<n; index++)
{
int k = arr[index];
if(k==0)
continue;
if(k==1)
{
prevNode = prevNode->next;
continue;
}
//To reverse LL in groups of k
int count = k;
currNode = prevNode->next;
nextNode = currNode->next;
//because it's in groups of "k"
while(count!=1)
{
//to prevent NULL ptr exception
if(nextNode == NULL)
return dummy->next;
currNode->next = nextNode->next;
nextNode->next = prevNode->next;
prevNode->next = nextNode;
nextNode = currNode->next;
count--;
}
prevNode = currNode;
if(nextNode == NULL)
return dummy->next;
}
return dummy->next;
}