Pattern visualizer
Delete Node in Linked List
Deleting from a singly linked list normally means pointing the previous node past the victim, but here the previous node cannot be reached: links run one way and the head is not provided. What is reachable is the successor. Copying its value into the given node makes the two nodes interchangeable, and unlinking the successor — which the given node CAN do, because it owns that pointer — leaves a list that reads exactly as if the original value had been removed. It only works because the problem promises the node is not the tail; a tail has no successor to impersonate. Animated on: list = [4, 5, 1, 9], delete the node holding 5 given ONLY that node — no head, no previous node. Result: [4, 1, 9]..
No predecessor? Become the successor, then delete it instead
List = [4, 5, 1, 9]. The only thing handed over is node (value 5, position 1) — no head, no predecessor. A normal delete rewires the node BEFORE the target, and that node is unreachable from here.
1FUNCTION deleteNode(node)2 nxt <- node.next3 node.val <- nxt.val4 node.next <- nxt.next5 RETURN
← / → step · space play · Home restart