# Delete N nodes after M nodes of a linked list in C++?

C++Server Side ProgrammingProgramming

Let us first define our linked list that contains data and the pointer to the next node.

struct Node {
int data;
struct Node* next;
};

We then create our createList(Node ** headPtr, int new_data) function which takes a doublePointer to the Node and an int value. Inside the function we assign the newly created node next pointer to the headptr and then the headptr to the newly created node.

void createList(Node ** headPtr, int new_data){
Node* newNode = new Node();
newNode->data = new_data;
}

The deleteNnodesAfterM(Node *head, int M, int N) method takes the root node and the M and the N values. Inside we assign Node* current to the head and also declare Node *t.

void deleteNnodesAfterM(Node *head, int M, int N){
int nodeCount;

Inside the function we have a while loop which runs while the current doesn’t point to null. The first for loop runs for M iterations. After the first for loop finish executing the current pointer points to the node after M in the linked list. The Node *t is then assigned the value current->next which is the first value to be deleted.

while (current){
for (nodeCount = 1; nodeCount < M && current!= NULL; nodeCount++)
current = current->next;
if (current == NULL)
return;
t = current->next;

The second for loop runs for N iterations and frees the N number of nodes from the starting position. The current->next is then assigned to t and t becomes our current node.

for (nodeCount = 1; nodeCount<=N && t!= NULL; nodeCount++){
Node *temp = t;
t = t->next;
free(temp);
}
current->next = t;
current = t;

void printList(Node *head){
while (temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}

## Example

Let us look at the following implementation to delete N nodes after M nodes of a linked list −

Live Demo

#include <iostream>
using namespace std;
struct Node{
int data;
Node *next;
};
void createList(Node ** headPtr, int new_data){
Node* newNode = new Node();
newNode->data = new_data;
}
while (temp != NULL){
cout<<temp->data<<" ";
temp = temp->next;
}
cout<<endl;
}
void deleteNnodesAfterM(Node *head, int M, int N){
int nodeCount;
while (current){
for (nodeCount = 1; nodeCount < M && current!= NULL; nodeCount++)
current = current->next;
if (current == NULL)
return;
t = current->next;
for (nodeCount = 1; nodeCount<=N && t!= NULL; nodeCount++){
Node *temp = t;
t = t->next;
free(temp);
}
current->next = t;
current = t;
}
}
int main(){
int M=2, N=2;
cout << "M = " << M<< " N = " << N<<endl;
return 0;
}

## Output

The above code will produce the following output −

M = 2 N = 2

14 12 6 4