Delete Node in a Linked List
You are given a reference to one node inside a singly linked list — the node to delete — and nothing else: no head, no way to reach the list from the front. Remove that node so the list's values read exactly as if it were gone, in place. Nothing is returned. It is guaranteed the node is not the tail, so a successor always exists.
- The number of nodes in the given list is in the range [2, 1000]
- -1000 <= Node.val <= 1000
- The node to be deleted is in the list and is not a tail node
head = [4,5,1,9], node = 5[4,1,9]head = [4,5,1,9], node = 1[4,5,9]Deleting a node usually requires its "predecessor" (the node before it) to rewire the chain. But what if you only have a reference to the target node itself? In a singly linked list, you cannot look backward.
Since we can't delete ourselves by telling our predecessor to skip us, we do something clever: we steal the identity of our neighbor.
We copy the value and the pointer from the node after us into our own node. Effectively, we become our successor, and the original successor becomes redundant and is skipped.
# 1. Steal the value of the next node
node.val = node.next.val
# 2. Skip the next node by taking its pointer
node.next = node.next.nextThis "trick" only works if there is a next node to steal from. If the target is the Tail, this approach is impossible without a reference to the head.
O(1) Identity Theft
Identify target node (5)