Skip to content

Linked lists and reference reversal

A singly linked list stores one value and one reference to the next node in each node. The head identifies the first node, and None marks the end. Python does not provide a built-in singly linked list type; interview platforms usually supply a node class.

A Python list is a dynamic array of references, not a linked list. Reading its position i takes O(1), while reaching position i in a singly linked list requires a traversal. The invented example below stores 4, 7, and 9 in separate nodes.

This node class uses dataclass to generate its initializer. Setting eq=False preserves identity comparisons between nodes. Two nodes with equal values are still different nodes. Every function in this lesson assumes an acyclic chain.

from dataclasses import dataclass
@dataclass(eq=False)
class Node:
"""One node in a singly linked integer list.
Attributes:
value: The integer stored at this node.
next: The following node, or None at the end of the list.
"""
value: int
next: "Node | None" = None
def make_list(values: list[int]) -> Node | None:
"""Build a linked list in the same order as the input values.
Args:
values: Integers to place in newly allocated nodes.
Returns:
The first node, or None for an empty input.
"""
head = None
for value in reversed(values):
head = Node(value, head)
return head
def list_values(head: Node | None) -> list[int]:
"""Collect values from an acyclic singly linked list.
Args:
head: The first node, or None for an empty list.
Returns:
Node values in traversal order.
"""
values = []
current = head
while current is not None:
values.append(current.value)
current = current.next
return values
head = make_list([4, 7, 9])
print("Traversal:", list_values(head))
print("Empty traversal:", list_values(None))
Traversal: [4, 7, 9]
Empty traversal: []

The head is a reference, not a container holding all nodes. An insertion after a known node changes a fixed number of references, giving O(1) time. Finding that node first can take O(n). Deleting a node in a singly linked list generally needs its predecessor or special handling at the head.

Reverse the node order without allocating replacement nodes. Maintain previous, which starts the reversed prefix, and current, which starts the untouched suffix. Save current.next before changing it; otherwise, the remaining suffix can become unreachable from these variables.

def reverse_list(head: Node | None) -> Node | None:
"""Reverse an acyclic singly linked list by changing its links.
Args:
head: The first node of the list to modify, or None.
Returns:
The first node after reversal, or None for an empty list.
"""
previous = None
current = head
while current is not None:
following = current.next
current.next = previous
previous = current
current = following
return previous
current = make_list([4, 7, 9])
previous = None
print("Initial reversed:", list_values(previous))
print("Initial untouched:", list_values(current))
while current is not None:
following = current.next
current.next = previous
previous = current
current = following
print("Reversed:", list_values(previous))
print("Untouched:", list_values(current))
head = make_list([4, 7, 9])
old_head = head
head = reverse_list(head)
print("Reversed traversal:", list_values(head))
print("Traversal from old head:", list_values(old_head))
Initial reversed: []
Initial untouched: [4, 7, 9]
Reversed: [4]
Untouched: [7, 9]
Reversed: [7, 4]
Untouched: [9]
Reversed: [9, 7, 4]
Untouched: []
Reversed traversal: [9, 7, 4]
Traversal from old head: [4]

Before each iteration, the two chains contain all original nodes without overlap. The reversed chain contains the processed prefix in reverse order. The iteration transfers one node from the untouched chain to that reversed chain, preserving the invariant. When current is None, the reversed chain contains every node.

The caller must keep the returned head. Its original head now identifies the tail, so a traversal from that old reference no longer visits the whole list.

For n nodes, reversal changes one link per node and takes O(n) time. Its three working references require O(1) auxiliary space. The existing nodes remain allocated; O(1) auxiliary space does not mean the input occupies constant space.

make_list allocates O(n) nodes, and list_values allocates an O(n) output list. The trace repeatedly collects both chains, so its display work takes O(n²). These display allocations are absent from reverse_list.

assert reverse_list(None) is None
single = Node(6)
assert reverse_list(single) is single
assert single.next is None
head = make_list([2, 2, 5])
assert list_values(reverse_list(head)) == [5, 2, 2]
print("Boundary checks passed.")
Boundary checks passed.
  • Solve Reverse Linked List with three references. Trace the untouched suffix before changing any link.
  • Solve Linked List Cycle with two moving references. Compare node identity rather than node values.

Download the Python source to run the complete example locally.

Open Data Structures on singly linked lists explains nodes, head references, and endpoint operations. It connects the representation to operation costs.

Python’s dataclass documentation explains generated initializers and the eq option. Those options define the small node class used here.