NeetCode #311LC-1474EasyLinked ListNC Algo100
← Back to All Problems#311 · #1474 · Delete N Nodes After M Nodes of a Linked List(删除链表 M 个节点之后的 N 个节点)
📌 Problem Statement & Constraints
Given the head of a linked list and two integers
m and n, traverse the list and delete n nodes after keeping m nodes, repeating until the end. Return the head. Constraints: 1 <= m, n <= 1000, the number of nodes is at most 10^4.💡 Core Algorithmic Approaches
- Keep a pointer
curat the last node of a kept block. - Advance
m - 1steps to reach the end of the kept block, then skipnnodes to find the next kept node. - Link
cur.nextto that node and continue. - The loop terminates when there are no more nodes to process.
💻 Benchmark Python3 Implementation
class Solution:
def deleteNodes(self, head: Optional[ListNode], m: int, n: int) -> Optional[ListNode]:
cur = head
while cur:
# keep m nodes: advance m-1 from cur
for _ in range(m - 1):
if cur is None:
break
cur = cur.next
if cur is None:
break
# delete the next n nodes
nxt = cur.next
for _ in range(n):
if nxt is None:
break
nxt = nxt.next
cur.next = nxt # relink past the deleted block
cur = nxt
return head⚡ Complexity Deep Dive
⏱️ Time Complexity
O(L): each node is visited once.
💾 Space Complexity
O(1): pointer manipulation only.
⚠️ Interview Pitfalls & Follow-ups
- Advancing
msteps instead ofm - 1:curstarts at the first kept node, so onlym - 1further steps are needed. - Deleting
n + 1nodes: the block to delete is exactlynnodes after the kept block. - Forgetting the
Noneguards: the list may end in the middle of a kept or deleted block. - Building a new list: the nodes should be relinked in place.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🧩 Related Linked List Problems
中文速览与面试要点
删除链表 M 个节点之后的 N 个节点
给定链表 head 和两个整数 m 和 n。遍历链表,删除下标从 m 到 n 的节点(保留前 m 个,删除接下来的 n 个),重复此过程直到到达链表末尾。返回修改后的链表。约束:1 ≤ m, n ≤ 1000;链表节点数在 [1, 10^4] 内;1 ≤ Node.val ≤ 10^6。
核心要点
- 两段式循环(标准解) :外层循环直到 cur 为空;内层先前进 m − 1 步(保留 m 个),再前进 n 步定位到删除区间的末尾,然后 cur.next = tmp.next 接上后续。
- 为什么保留 m 个只需走 m − 1 步 : cur 本身就算作保留的第一个节点。
- 边界处理 :若中途 cur 或 tmp 变为 None,说明已到末尾,直接结束。
- 复杂度 :O(n),每个节点最多被访问一次。
常见陷阱
- 保留阶段走 m 步 :会让 cur 停在保留区间的最后一个节点 之后 ,多保留一个节点。应为 m − 1 步。
- 删除阶段不检查越界 : tmp.next 可能为 None,直接访问会抛 AttributeError。
- cur.next = tmp.next 写成 cur = tmp.next :前者是接上链表,后者只是移动指针,没有真正删除。
- 忘记最后 cur = cur.next :会导致死循环(cur 停在原位反复处理同一段)。
参考实现
class Solution:
def deleteNodes(self, head: 'ListNode', m: int, n: int) -> 'ListNode':
cur = head
while cur:
# ① 保留 m 个节点(cur 本身算一个,故只走 m-1 步)
for _ in range(m - 1):
if cur.next is None:
return head
cur = cur.next
# ② 从 cur 之后删除 n 个节点
tmp = cur
for _ in range(n):
if tmp.next is None:
break
tmp = tmp.next
# ③ 接上后续
cur.next = tmp.next
cur = cur.next
return head