Remove Node

Remove Node

Remove the first node whose value equals target and return the head of the resulting list. If no node matches, return the list unchanged.

removeNode(head, target)

Input format: list | target. Output the resulting list, space-separated.

Examples

(1 → 2 → 3), 2   // → 1 → 3
(1 → 2 → 3), 1   // → 2 → 3   (removing the head)
(1 → 2 → 3), 9   // → 1 → 2 → 3

Walkthrough

Thinking it through

Removing a node isn't about the node itself — it's about the node before it. Since a singly linked list only has forward pointers, the only way to "remove" a node is to redirect its predecessor's next past it. You can never operate on the node you want to delete directly; you always need a handle on what comes before it.

The special problem of deleting the head

This creates an awkward asymmetry: every middle or tail node has a natural predecessor to adjust, but the very first node has none — there's nothing before it whose next you could redirect. Handled literally, that means a separate branch: "if the head is the target, just move the head pointer instead of splicing."

The dummy-head trick removes the asymmetry

Invent a placeholder node just before the real head, pointing at it. Now every node — including the original head — has a predecessor: for the head, that's the dummy. The exact same logic ("look at prev's next; if it matches, splice it out") handles the head, middle, or tail with no special-casing. At the end, the real answer is the dummy's next.

Building the approach

  1. Create the dummy, pointing at the original head.
  2. Walk a "previous" pointer from the dummy, always looking one node ahead (previous.next).
  3. At each step, check whether previous.next's value equals the target. If it does, redirect previous.next to skip past it, and stop — only the first match should be removed.
  4. If not, advance and keep looking.
  5. If you reach the end without a match, nothing gets removed, and the list comes back unchanged.

Why this is efficient

Each node is inspected at most once, with an early exit the moment a match is found — linear time in the worst case, and the extra state (the previous pointer and the dummy) doesn't grow with list size.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.