Select Page

Delete N nodes after M nodes of a linked list

In this problem, we have given a linked list and two integers M and N. We need to traverse the linked list in such a way that we retain M nodes of the linked list and delete N nodes of the linked list continually till the end of the linked list.

Examples:

Input:

M = 3, N = 2

Linked List: 2 ->4 ->6 ->8 ->10 ->12 ->14 ->16

Output:

Linked List: 2 -> 4 -> 6 -> 12 -> 14 -> 16

Input:

M = 1, N = 3

Linked List: 0 -> 12 -> 13 ->4 -> 15 ->6 -> 17 ->8 -> 19

Output:

Linked List: 0 -> 15 -> 19

Input:

M = 1, N = 1

Linked List: 1 ->2 ->3 ->4 ->5 ->6 ->7 ->8 ->9 ->10

Output:

Linked List: 1 ->3 ->5 ->7 ->9

Method:

This method will traverse the given linked list and skip the first m nodes and then delete the next n nodes. It performs this traversing for all the remaining nodes. Here, we need to handle all corner case or boundary conditions and maintain proper links between the nodes of the linked list.

C program to delete N nodes after M nodes of a linked list

Output:

Time Complexity: The time complexity of the above method is O(n), where n is the total number of nodes in the linked list.