-
Notifications
You must be signed in to change notification settings - Fork 0
/
33. ReverseNodesInKGroups.cpp
67 lines (53 loc) · 1.18 KB
/
33. ReverseNodesInKGroups.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
#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 b[]){
if (head == NULL) {
return NULL;
}
int ind = 0;
Node *prev = NULL, *cur = head, *next = NULL;
Node *tail = NULL, *join = NULL;
bool isHeadUpdated = false;
while(cur!=NULL and ind<n){
int k = b[ind];
if(k==0){
ind++;
continue;
}
join = cur;
prev = NULL;
while(cur!=NULL and k--){
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
if (isHeadUpdated == false) {
head = prev;
isHeadUpdated = true;
}
if (tail != NULL) {
tail->next = prev;
}
tail = join;
ind++;
}
if (tail != NULL) {
tail->next = cur;
}
// Return the head of the linked list.
return head;
}