Delete N Nodes After M Nodes of a Linked List
This problem can be solved by simulating the process described in the problem statement. We’ll traverse the linked list, keeping m
nodes and then deleting n
nodes.
Approach
- Initialize two pointers,
current
andprev
. - Traverse the list using a loop.
- For each step, keep
m
nodes by simply moving the current pointer. - Delete
n
nodes by adjusting thenext
pointer of theprev
node. - Repeat steps 3-4 until the end of the list.
Here’s the code implementing this approach:
|
|
Example
Let’s take head = [1,2,3,4,5,6,7,8,9,10,11,12,13], m = 2, n = 3
as an example:
- Keep 2 nodes:
1,2
. - Delete 3 nodes:
3,4,5
. - Keep 2 nodes:
6,7
. - Delete 3 nodes:
8,9,10
. - Keep 2 nodes:
11,12
. - Result:
[1,2,6,7,11,12]
.
Complexity
This solution has a time complexity of O(N) and a space complexity of O(1), where N is the number of nodes in the linked list.