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
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)