# Repeatedly Delete N nodes after M nodes of a Linked list

Given a linked list and two integers M and N. Traverse the linked list such that you retain M nodes then delete next N nodes, continue the same until end of the linked list.

Input:
M = 2, N = 2
Output:

The main part of the problem is to maintain proper links between nodes, make sure that all corner cases are handled.

Implementation:

```typedef struct _Node
{
int data;
}Node;

// Function to skip M nodes and then remove N nodes of the linked list.
void SkipAndRemove( node  *head, int M, int N)
{
int count;

while (current)
{
// Skip M nodes
for (count = 1; count<M && current!= NULL; count++)

// If we reached end of list, then return
if (current == NULL)
return;

// Start from link node and remove N nodes
for (count = 1; count<=N && t!= NULL; count++)
{
node *temp = t;
free(temp);
}

// Set current pointer for link iteration
current = t;
}
}
```

Time Complexity: O(n) where n is number of nodes in linked list.

### 2 Thoughts on “Repeatedly Delete N nodes after M nodes of a Linked list”

1. praful Pjdurkar on May 24, 2015 at 1:35 am said:

This will work for java

int M =2, N=3;
int index = 0;
while(index<=ll.size()) {
index += M ;
System.out.println(index);
int count = 0;
while(countll.size()-1) {
continue;
}
else {
ll.remove(index);
// index++;
}

}
}
System.out.println(ll);

}

2. Bharath Reddy on April 6, 2016 at 11:18 pm said:

Java code:
public ListNode retainMdeleteNnodes(ListNode headNode, int m, int n){
if(m == 0){
System.out.println(“All nodes deleted”);
return null;
}else if (n == 0 || size <= m){
}
int retain = 1;
while(retain < m ){
retain++;
retainNode = retainNode.getNext();
}
if(size <= m+n){
retainNode.setNext(null);