Change the chain carefully.
Handle head deletion and missing values as explicit cases.
01 Model the idea
Linked-list operations combine a search with link updates. A sentinel before the head makes deleting the first real node look like deleting an interior node. Keep previous and current references while scanning; when a match is found, reconnect previous.next to current.next. State whether deletion removes the first occurrence or every occurrence.
The prefix before current remains connected and contains no removed match.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
ADD a sentinel before the head
SCAN while keeping previous and current
ON first match: reconnect previous to current.next
RETURN sentinel.next03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class Node:
def __init__(self, value, next=None): self.value, self.next = value, next
def remove_first(head, target):
sentinel = Node(None, head)
previous, current = sentinel, head
while current:
if current.value == target:
previous.next = current.next
return sentinel.next
previous, current = current, current.next
return sentinel.next
head = Node(1, Node(2, Node(1)))
head = remove_first(head, 1)
values = []
while head: values.append(head.value); head = head.next
print(values)[2, 1]
- 1
The sentinel is not part of the returned data. Its next field always names the possibly changed head.
- 2
Only the first matching node is removed. Returning immediately makes the duplicate policy visible.
- 3
Deleting a missing value leaves the chain unchanged. Include empty input, head, tail, singleton, and duplicate cases in tests.
04 Count the cost
O(n) search and deletion together
O(1) auxiliary
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Test deletion from an empty list and deletion of the only node.
Reveal one possible solution +
class Node:
def __init__(self, value, next=None): self.value, self.next = value, next
def remove_first(head, target):
sentinel = Node(None, head)
previous, current = sentinel, head
while current:
if current.value == target:
previous.next = current.next; break
previous, current = current, current.next
return sentinel.next
assert remove_first(None, 1) is None
assert remove_first(Node(1), 1) is None
print("Boundary checks passed")06 Check your reasoning
Why return a possibly new head?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.