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.
(1 → 2 → 3), 2 // → 1 → 3
(1 → 2 → 3), 1 // → 2 → 3 (removing the head)
(1 → 2 → 3), 9 // → 1 → 2 → 3
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.
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."
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.
previous.next).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.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.
def remove_node(head, target):
dummy = ListNode(0)
dummy.next = head
prev = dummy
while prev.next is not None:
if prev.next.val == target:
prev.next = prev.next.next
break
prev = prev.next
return dummy.next
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.