-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path28-delete-n-nodes-after-m-nodes-of-a-linked-list.cpp
132 lines (113 loc) · 2.1 KB
/
28-delete-n-nodes-after-m-nodes-of-a-linked-list.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include<stdio.h>
#include<stdlib.h>
#include<iostream>
using namespace std;
/* A linked list node */
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
struct Node *start = NULL;
/* Function to print nodes in a given linked list */
void printList(struct Node *node)
{
while(node != NULL)
{
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
void insert(int n1)
{
int n,value;
n=n1;
struct Node *temp;
for(int i=0;i<n;i++)
{
cin>>value;
if(i==0)
{
start = new Node(value);
temp=start;
continue;
}
else
{
temp->next = new Node(value);
temp=temp->next;
}
}
}
// } Driver Code Ends
/*
delete n nodes after m nodes
The input list will have at least one element
Node is defined as
struct Node
{
int data;
struct Node *next;
Node(int x){
data = x;
next = NULL;
}
};
*/
class Solution
{
public:
void linkdelete(struct Node *head, int M, int N)
{
Node* trav = head;
while(trav)
{
int count = M;
while(count > 1 && trav)
{
trav = trav->next;
count--;
}
count = N;
Node* curr = trav;
while(count && curr)
{
curr = curr->next;
count--;
}
if(trav && curr)
{
trav->next = curr->next;
trav = trav->next;
}
else if(trav)
{
trav->next = NULL;
trav = trav->next;
}
}
}
};
// { Driver Code Starts.
int main()
{
int t,n1;
cin>>t;
while (t--) {
cin>>n1;
int m,n;
cin>>m;
cin>>n;
insert(n1);
Solution ob;
ob.linkdelete(start,m,n);
printList(start);
}
return 0;
}
// } Driver Code Ends