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;
}
}
本文介绍了一种在单链表中每隔m个节点删除n个节点的算法实现。通过遍历链表,维护两个指针分别指向当前节点及前一个节点,调整指针完成删除操作。适用于数据结构与算法初学者。
5003

被折叠的 条评论
为什么被折叠?



