Follow a linked chain through next references, then change only the edges you own. Preserve the untouched successor before relinking, return the new head when it moves, and distinguish an O(1) local edit from locating or copying nodes.
Recognize it when The input is already a node chain and the answer depends on relinking it.
Checking your account…
Linked List Code Labs
Mental Model
A linked list stores order in references, not in adjacent array positions. A node owns a value and
a next reference; the head is the only external entry point required to reach the chain. There is
no constant-time list[index] operation. To reach the kth node, follow k links.
In the Labs, an integer array represents those references: next_indices[node] is the next node or
-1. The representation makes pointer changes observable without hiding the central ownership
rule inside a helper class. These Labs assume valid indices and a finite acyclic chain; the
sentinel bypass also assumes its removal target is reachable from the head. A cyclic chain needs
a separate cycle-detection contract before this traversal can terminate.
Nodes, References, and Ownership
Python variables hold references to node objects. Two names may alias the same node, so changing
node.next is visible through every alias. Reassigning the local variable node only moves that
one cursor; it does not change the chain.
The key question before mutation is: which reference owns the edge being replaced? Removing a node
means updating its predecessor’s next, or updating the external head when there is no predecessor.
Traverse Without Random Access
Start at the head and repeatedly follow next. Before each step, the output contains exactly the
nodes already visited in chain order, and the cursor names the next unvisited node. This scan is
O(n) time and O(1) auxiliary space when it only aggregates; materializing visited values costs O(n)
output space.
Follow a Linked Chain
Reference
def chain_order(next_indices, head):
order = []
current = head
while current != -1:
order.append(current)
current = next_indices[current]
return order
Practice
Implement chain_order(next_indices, head). Follow next references from head until -1 and return the visited node indices in chain order. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain.
Public tests
Verify reference order wins
Verify empty head boundary
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Follow a Linked Chain
def chain_order(next_indices, head):
order = []
current = head
while current != -1:
order.append(current)
current = next_indices[current]
return order
Relink Without Losing the Suffix
Pointer updates must preserve the successor before overwriting the edge that reaches it. During
reversal, keep three meanings stable: previous is the reversed prefix head, current is the next
node to move, and successor preserves the untouched suffix. Then redirect current.next, advance
both boundaries, and repeat.
Reverse Links Safely
Reference
def reverse_chain(next_indices, head):
links = next_indices.copy()
previous = -1
current = head
while current != -1:
successor = links[current]
links[current] = previous
previous = current
current = successor
return links, previous
Practice
Implement reverse_chain(next_indices, head). Return a copied next-index array and the new head after reversing only the reachable chain. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain.
Public tests
Verify successor preservation
Verify input links stay unchanged
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Reverse Links Safely
def reverse_chain(next_indices, head):
links = next_indices.copy()
previous = -1
current = head
while current != -1:
successor = links[current]
links[current] = previous
previous = current
current = successor
return links, previous
Trace Successor Preservation During Reversal
Use the reversal Lab on links [1, 2, -1] with head 0. The saved successor keeps the unreversed suffix reachable while each edge turns backward. The function copies its link array, so it returns both the new storage and a new head.
print(reverse_chain([1, 2, -1], 0)) followed by print(reverse_chain([], -1))
Step
Executed statement
State
Why
1
links = next_indices.copy(); previous = -1; current = head
links = [1, 2, -1]; previous = -1; current = 0
A copied array preserves input ownership; no node has moved yet.
2
successor = links[current]; links[current] = previous
successor = 1; links = [-1, 2, -1]
Save node 1 before overwriting the edge that reaches it.
3
previous = current; current = successor
previous = 0; current = 1
The reversed prefix grows by one while the untouched suffix remains reachable.
4
successor = links[current]; links[current] = previous; previous = current; current = successor
links = [-1, 0, -1]; previous = 1; current = 2
Node 1 now reaches the already reversed prefix; saved successor advances to node 2.
5
successor = links[current]; links[current] = previous; previous = current; current = successor
links = [-1, 0, 1]; previous = 2; current = -1
The end marker terminates traversal and previous is the new entry point.
6
return links, previous
result = ([-1, 0, 1], 2)
Both the changed edges and the head are needed to describe the reversed chain.
Print
Output
1
([-1, 0, 1], 2)
2
([], -1)
After the last iteration, previous names node 2 and current reaches -1. Returning the old head 0 would expose only the former first node. Copying is part of this Lab’s ownership contract and costs linear space even though the pointer transition uses only a few cursors.
If successor is read after the redirect, the original suffix is no longer reachable from the
cursor. This is the linked-list version of overwriting data before saving it.
Use a Sentinel for Head Boundaries
A sentinel is a temporary predecessor whose next points at the real head. It lets deletion use
the same “predecessor skips target” transition even when the target is currently first. Return the
sentinel’s updated successor as the new head; the sentinel itself is not part of the result.
Implement bypass_node(next_indices, head, remove_index). Use a temporary sentinel predecessor and return copied links plus the possibly changed head. Inputs describe a finite acyclic reachable chain with valid node indices or -1 links; head is -1 only for an empty reachable chain. remove_index is a valid node reachable from head.
Public tests
Verify middle-node bypass
Verify sentinel head update
Loading interactive editor.If it does not appear, the reference and starter code remain readable.Reload editor
Sentinels simplify control flow but do not remove the need for a contract. Decide whether the target
is guaranteed to exist and whether the removed node must be detached for memory or API semantics.
Choose a Linked List or Another Structure
Choose a linked list when the input is already node-based and the task depends on local relinking,
streaming merge, or constant-space reversal. Choose a Python list when indexed access dominates;
its compact built-in representation is usually faster and simpler. Choose a deque for an ordinary
queue instead of manually maintaining nodes.
Linked lists do not make arbitrary deletion O(1) unless the operation already owns the predecessor
or the node contract provides enough local references. Searching for the deletion point remains
O(n).
Linked Reference and Head Mistakes
Advancing before saving the successor can lose the rest of the chain.
Returning the old head after reversal exposes only the former first node.
Comparing node values instead of node identity can break problems with duplicate values.
Mutating a shared input when the function promises a new chain violates alias expectations.
Forgetting an empty head or one-node chain often produces an attribute error or stale reference.
Explain It in an Interview
Name each cursor by meaning before coding: predecessor, current, successor, or sentinel. State which
part of the chain is already final and which edge still connects to untouched nodes. Draw one
three-node example, then verify the empty and head-changing cases. Complexity follows from how many
times each link is visited; pointer assignment is constant time, but locating a node may require a
full traversal.
tail is always the last node of the answer so far.
Return dummy.next, never dummy.
How problems bend it
Remove the n-th node from the end: Start two pointers at the dummy, move one n + 1 steps ahead, then move both.
Add two numbers: Same tail-building loop, plus a carry.
Reverse a linked list
Save next, point back, step forward.
You need a list (or part of it) in reverse order without extra space.
Trigger words
reverse a linked list
reverse k-group
reorder list
palindrome linked list
second half reversed
def reverse_list(head):
prev = None
curr = head
while curr:
next_node = curr.next # 1. save the rest of the list
curr.next = prev # 2. point this node backwards
prev = curr # 3. move prev forward
curr = next_node # 4. move curr forward
return prev # prev is the new head
Spot it when
Reverse a list or a group of k nodes.
Compare the first half with the second half.
Remember
Always save curr.next before you overwrite it.
When the loop ends, curr is None and prev is the old tail.
How problems bend it
Reorder or palindrome list: Find the middle with fast/slow pointers, reverse the second half, then walk both halves.
Reverse in groups of k: Check that k nodes exist, reverse them with this loop, and reconnect the group.
Python Version Note
Python 3.11+
The examples use standard Python containers and syntax available in the supported browser runtime; Linked List itself is taught as an interview abstraction.