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

  1. Use a dummy head so removing the original head needs no special case.
  2. Keep a pointer cur at the node whose successor is being examined.
  3. If the successor matches, unlink it; otherwise advance.
  4. 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 cur must stay put.
  • Omitting the dummy head: removing the head would need a separate branch.
  • Returning head: the original head may have been removed; return dummy.next.
  • Handling an empty list: the loop does not execute and dummy.next is None, which is correct.