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


In this tutorial, we are going to learn how to delete N nodes after M nodes in a linked list.

Let's see the steps to solve the problem.

  • Write a struct Node for the linked list node.

  • Initialize the linked list with the dummy data.

  • Write a function to delete N nodes after M nodes.

    • Initialize a pointer with the head pointer.

    • Iterate till the end of the linked list.

    • Move the pointer to the next node until M nodes.

    • Delete the N nodes

    • Move the pointer to the next node

  • Print the linked list

Example

Let's see the code.

 Live Demo

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *next;
};
void insertNode(Node ** head_ref, int new_data) {
   Node* new_node = new Node();
   new_node->data = new_data;
   new_node->next = (*head_ref);
   *head_ref = new_node;
}
void printLinkedList(Node *head) {
   Node *temp = head;
   while (temp != NULL) {
      cout<< temp->data << " -> ";
      temp = temp->next;
   }
   cout << "Null" << endl;
}
void deleteNNodesAfterMNodes(Node *head, int M, int N) {
   Node *current = head, *temp;
   int count;
   while (current) {
      // skip M nodes
      for (count = 1; count < M && current!= NULL; count++) {
         current = current->next;
      }
      // end of the linked list
      if (current == NULL) {
         return;
      }
      // deleting N nodes after M nodes
      temp = current->next;
      for (count = 1; count <= N && temp != NULL; count++) {
         Node *deletingNode = temp;
         temp = temp->next;
         free(deletingNode);
      }
      current->next = temp;
      current = temp;
   }
}
int main() {
   Node* head = NULL;
   int M = 1, N = 2;
   insertNode(&head, 1);
   insertNode(&head, 2);
   insertNode(&head, 3);
   insertNode(&head, 4);
   insertNode(&head, 5);
   insertNode(&head, 6);
   insertNode(&head, 7);
   insertNode(&head, 8);
   insertNode(&head, 9);
   cout << "Linked list before deletion: ";
   printLinkedList(head);
   deleteNNodesAfterMNodes(head, M, N);
   cout << "Linked list after deletion: ";
   printLinkedList(head);
   return 0;
}

Output

If you run the above code, then you will get the following result.

Linked list before deletion: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null
Linked list after deletion: 9 -> 6 -> 3 -> Null

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 27-Jan-2021

720 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements