VOOZH about

URL: https://www.geeksforgeeks.org/dsa/delete-n-nodes-after-m-nodes-of-a-linked-list/

⇱ Delete N nodes after M nodes of a linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Delete N nodes after M nodes of a linked list

Last Updated : 11 Dec, 2024

Given a linked list and two integers m and n, the task is to traverse the linked list such that you skip m nodes, then delete the next n nodes, and continue the same till end of the linked list.

Note: m cannot be 0.

Example

Input: Linked List: 9->1->3->5->9->4->10->1, n = 1, m = 2

👁 Image

Output: 9->1->5->9->10->1

👁 Image

Explanation: Deleting 1 node after skipping 2 nodes each time, we have list as 9-> 1-> 5-> 9-> 10-> 1.

Input: Linked List: 1->2->3->4->5->6, n = 1, m = 6

👁 Image

Output: 1->2->3->4->5->6

👁 Image

Explanation: After skipping 6 nodes for the first time , we will reach of end of the linked list, so, we will get the given linked list itself.

The idea is to go through a linked list and, for every set of nodes, keep the first m nodes and delete the next n nodes, and then repeat this process until the end of the list.

Step-by-step approach:

  • Start with a pointer at the first node (the head) of the linked list.
  • Move this pointer forward m times, so it skips over m nodes.
  • After skipping m nodes, the next n nodes should be deleted.
    • To do this, we disconnect these n nodes from the list and free their memory.
  • After deleting the n nodes, repeat the process starting from the next node. Skip the next m nodes and delete the following n nodes.
  • This process will stops when we reach to end of the list, either because there are fewer than m nodes left to skip or there are no nodes left to delete.

Below is the implementation of the above approach:


Output
1 2 5 6 

Time Complexity: O(n), where n is the total number of nodes in the linked list. This is because the algorithm processes each node exactly once, either by skipping it or by deleting it.
Auxiliary Space: O(1)

Comment
Article Tags: