Delete N nodes after M nodes of a Linked List

Problem Statement

There is a linked list and two integers M and N. Traverse the linked list such that it retains M nodes then delete the next N nodes, continue the same till the end of the linked list.

M = 2, N = 2
Linked List: 1->2->3->4->5->6->7->8
Linked List: 1->2->5->6


This can be solved by skipping N nodes after the traversal of M nodes.

Linked List Class and method to display all nodes.

class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val = next

def display(lst):
while lst != None:
lst =

Delete N nodes after M Nodes:

def deleteNNodes(head, n, m):
if head == None:
return None

current = head
prev = None
skipped = m
deleted = n
while current != None:
if skipped > 0:
prev = current
current =
skipped -= 1
elif skipped == 0:
if deleted > 0:
current =
deleted -= 1

if deleted == 0: = current
skipped = m
deleted = n

return head


l1 = ListNode(1) = ListNode(2) = ListNode(3) = ListNode(4) = ListNode(5) = ListNode(6) = ListNode(7) = ListNode(8) = ListNode(9) = ListNode(10)
m = 3
n = 2
print('---- Before Delete ---')
print('---- After Delete ---')
data = deleteNNodes(l1, n, m)

Time Complexity




Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gul Ershad

Gul Ershad

A technology explorer with the drive to learn, apply and expand his mind.