Linked lists
Track ownership of every link before rewriting it.
Choose ownership and identity contracts, preserve reachable suffixes, and prove temporary edits are restored when required.
Mechanism and state
For reversal, previous is the reversed prefix and current is the untouched suffix head. Save next=current.next before overwriting current.next. Redirect to previous, advance previous to current, then current to the saved next. The returned head is previous, while the old head becomes a null-terminated tail. For merging, choose the smaller remaining head (A on ties), link it after a dummy-backed tail, and attach the final suffix. Inputs must be sorted, acyclic, disjoint, and owned for mutation. For cycle detection, advance slow one and fast two edges under a null-safe guard, comparing references after movement. For entry recovery, reset only a new seeker to head, then move seeker and slow equally. Removal uses a validated n-edge dummy-to-fast gap before splicing and detaching. Reorder splits, reverses, and weaves two disconnected halves. Intersection switches heads on null to cancel unequal private prefixes. Palindrome reverses one half, compares values, and restores before either result. Addition carries bounded decimal columns into fresh nodes. Random-pointer copying interleaves adjacent copies, translates random through target.next, then restores and separates. LRU Cache combines exact key-to-node lookup with a private doubly linked recency list. Distinct HEAD/TAIL sentinels anchor most-recent and least-recent ends. A hit/update unlinks and reinserts the same node; an insertion at full capacity removes the tail-side real node from both representations.
Why the pattern works
At loop entry, the original nodes partition into a reversed prefix and original-order suffix. Saving the successor protects reachability; redirecting one edge and advancing moves exactly one object into the prefix. A finite acyclic suffix shrinks by one each step, establishing termination and full coverage. In a merge, the selected sequence ending at tail is the stable merge of consumed prefixes; tail.next may still lead into an unconsumed suffix. For Floyd, a meeting at positive time t means the distance difference t is divisible by cycle length L. With tail length μ, another μ equal-speed steps bring the meeting pointer and a fresh head pointer to entry; before μ steps they occupy disjoint tail and cycle regions. For removal the n-edge gap places slow just before the target when fast reaches the tail. For reorder, each weave consumes one node from each disjoint frontier. For restoration, reverse twice recovers internal edges and reconnecting the midpoint recovers the boundary. Interleaving establishes an identity bijection before random translation and preserves the remaining woven suffix during separation. At every public return, indexed keys and real linked nodes form a bijection, neighbor links agree, size respects capacity, and order matches last successful-get/put time. Private unlink/relink steps temporarily detach an indexed node; this is not a stable external state. A zero-capacity cache keeps only its empty sentinel structure.
Work through an example
For a(5)→b(5)→null, the result must be b→a→null, even though both displayed values are 5. Reversing twice should restore the original head and every original next reference, not merely the value sequence. With tail length 3 and cycle length 4, slow and fast meet at N4 after four rounds, then seeker and slow reach entry N3 after three recovery moves. With A0(2)→A1(2) and B0(2), stable merge returns A0→A1→B0 using the same objects. For [1,2,3,4,1], palindrome records the 2/4 mismatch yet restores all next references before false. For [9,9,9]+[1], emitted digits [0,0,0,1] are fresh and the last one comes entirely from carry. A random self-reference N1.random=N1 becomes C1.random=C1, never C1.random=N1. At capacity two, put(1),put(2),get(1) yields recency [1,2], so put(3) evicts two. Updating one keeps its exact node identity and does not evict a neighbor. A missing get and size read do not promote. Reinserting an evicted key creates a fresh node.
Where the reasoning fails
New nodes or swapped values can fake a reversed value array while violating identity. Advancing current through its overwritten link walks backward. Cyclic input needs a separate policy; this reversal contract assumes a finite acyclic list. A shared tail can make naive merge form a self-loop. In cycle detection, comparing at initialization falsely marks every list, and equal values do not establish a cycle. The meeting object is generally not the cycle entry. Restoring after return is impossible: palindrome must not early-return on mismatch. Random copying requires the entire spine woven before forward random translation and does not promise rollback on allocation failure. Equal values establish palindrome pairs but never establish graph identity or intersection. A map entry left behind after unlinking an eviction is a ghost resident. Forgetting either reciprocal link corrupts later promotions. A successful get mutates state, so a concurrent map alone cannot make the whole cache thread-safe. Stored −1 is distinguished from absence with OptionalInt.
Reconstruct the reasoning
Trace the four assignments for a three-node list. After each, name the references that still make the suffix reachable, and check the old head’s final next link. For each merge step distinguish the selected prefix from its still-linked suffix; for μ=3,L=4 record slow/fast detection positions and seeker/slow recovery positions. Check original edges remain unchanged for both cycle APIs. For each API state whether it is read-only, destructive, restoring on normal return, or allocates independent output. Trace deletion of the head, odd reorder, unequal-prefix intersection, mismatch restoration, final carry, and a forward random target. Validate edges and identities rather than only arrays of values. Draw both link directions before and after a capacity-one promotion and a capacity-two eviction. Mark which identities remain indexed during a private detached phase, explain the restored public bijection, and contrast cache-owned nodes with caller-owned destructive list operations.
Apply this foundation
- Reverse Linked List · Explanation
- Merge Two Sorted Lists · Explanation
- Linked List Cycle Detection · Explanation
- Find Linked List Cycle Entry · Explanation
- Remove Nth Node from End · Explanation
- Reorder List · Explanation
- Intersection of Two Linked Lists · Explanation
- Palindrome Linked List · Explanation
- Add Two Numbers — Reversed Digits · Explanation
- Copy List with Random Pointer · Explanation
- LRU Cache · Explanation