217. Delete Node in a Linked List
You are handed a reference to a single node inside a singly linked list — and not the list's head. Write delete_node(node) so that, after it runs, walking the list from its original head visits every original value except that node's, in the same relative order.
Two guarantees make this possible: every value in the list is distinct, and the given node is never the tail. Your function returns nothing; it mutates the list in place.
The catch: with no pointer to the previous node, you cannot do the usual prev.next = node.next rewiring. What can you change from where you stand?
Example 1:
Input: head = [4, 5, 1, 9], node = the node with value 5
Output: [4, 1, 9]
Explanation: You receive the node holding 5. After deletion the list reads 4 → 1 → 9.
Example 2:
Input: head = [4, 5, 1, 9], node = the node with value 1
Output: [4, 5, 9]
Explanation: You receive the node holding 1. After deletion the list reads 4 → 5 → 9.
Constraints:
- 2 ≤ number of nodes ≤ 1000
- -1000 ≤ Node.val ≤ 1000
- All node values are distinct.
- The node to delete is in the list and is never the tail.
Hints:
You can't reach the node before you, so the usual unlink is impossible. A linked list has two mutable things: links and values. Which one is still within reach?
Overwrite the node's value with its successor's value, then splice the successor out with `node.next = node.next.next`. To every outside observer, your node is gone — in O(1).
▶ Run checks these sample cases. Submit also runs hidden edge cases.
Input: head = [4, 5, 1, 9], node = the node with value 5
Expected output: [4, 1, 9]