Approach 1: Traverse Linked List and Delete In Place
Intuition
The singly linked list can be traversed linearly starting from the head node. As we must delete nn nodes after every mm nodes, we must traverse the first mm nodes, store the m^{th}m
th
node and then delete the next nn nodes. To delete the nn nodes, we must make the m^{th}m
th
node point to the node next to the n^{th}n
th
node.
Algorithm
Initialize the currentNode to the head of the linked list. currentNode is the pointer that will be used to traverse each node of the linked list linearly.
Iteratively delete nn nodes after mm node and continue until we reach the end of list.
Start by iterating mm nodes. As currentNode iterates over each node, we maintain a pointer lastMNode that points to the predecessor of currentNode. After mm iterations, the lastMNode points to the m^{th}m
th
node.
Now, continue iterating over nn nodes. After nn iterations, we must delete nodes between lastMNode and currentNode
To delete nn nodes, we could simply modify the next pointer of lastMNode to point to the currentNode.
The algorithm can be illustrated with the following example
class Solution {
public ListNode deleteNodes(ListNode head, int m, int n) {
ListNode currentNode = head;
ListNode lastMNode = head;
while (currentNode != null) {
// initialize mCount to m and nCount to n
int mCount = m, nCount = n;
// traverse m nodes
while (currentNode != null && mCount != 0) {
lastMNode = currentNode;
currentNode = currentNode.next;
mCount--;
}
// traverse n nodes
while (currentNode != null && nCount != 0) {
currentNode = currentNode.next;
nCount--;
}
// delete n nodes
lastMNode.next = currentNode;
}
return head;
}
}