NeetCode #307LC-203EasyLinked List
← Back to All Problems#307 · #203 · Remove Linked List Elements(移除链表元素)
📌 Problem Statement & Constraints
Given the head of a linked list and an integer
val, remove all nodes whose value equals val and return the new head. Constraints: the number of nodes is in [0, 10^4], 1 <= Node.val <= 50, 0 <= val <= 50.💡 Core Algorithmic Approaches
- Use a dummy head so removing the original head needs no special case.
- Keep a pointer
curat the node whose successor is being examined. - If the successor matches, unlink it; otherwise advance.
- This is the standard "delete by value" template.
💻 Benchmark Python3 Implementation
class Solution:
def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
dummy = ListNode(0, head)
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next # unlink, do not advance
else:
cur = cur.next
return dummy.next⚡ Complexity Deep Dive
⏱️ Time Complexity
O(n): one pass.
💾 Space Complexity
O(1): pointer manipulation only.
⚠️ Interview Pitfalls & Follow-ups
- Advancing after unlinking: the new successor has not been examined yet, so
curmust stay put. - Omitting the dummy head: removing the head would need a separate branch.
- Returning
head: the original head may have been removed; returndummy.next. - Handling an empty list: the loop does not execute and
dummy.nextisNone, which is correct.
⚡
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
中文速览与面试要点
移除链表元素
给你一个链表的头节点 head 和一个整数 val,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。约束:列表中的节点数目在范围 [0, 10^4] 内;1 ≤ Node.val ≤ 50;0 ≤ val ≤ 50。
核心要点
- 哑结点 + 单指针(标准解) :创建哑结点指向 head,用 cur 遍历,若 cur.next.val == val 则 cur.next = cur.next.next (跳过该节点),否则 cur = cur.next 。
- 哑结点的价值 :当需要删除头节点时,无需特判, dummy.next 会自动指向新的头。
- 为什么删除后不移动 cur : cur.next 已被替换成新节点,该节点尚未检查,必须留在原地再判一次。
- 复杂度 :单次遍历,O(n) 时间、O(1) 空间。
常见陷阱
- 删除后也移动 cur :会漏检紧随其后的连续待删节点。必须删除后不移动。
- 不引入哑结点 :删除头节点时需要额外循环处理,代码更繁琐。
- 循环条件写成 while cur :会访问 cur.next.val 时抛异常。应为 while cur.next 。
- 返回 head 而非 dummy.next :若头节点被删除, head 已失效。
参考实现
class Solution:
def removeElements(self, head: 'ListNode', val: int) -> 'ListNode':
dummy = ListNode(0, head)
cur = dummy
while cur.next:
if cur.next.val == val:
cur.next = cur.next.next # 跳过待删节点,cur 不动
else:
cur = cur.next
return dummy.next