Sub topic 3
Linked Lists and Their Nodes
This chapter assumes you can write basic Python with loops and functions, that you are comfortable with references (names that point to objects), and that you know O(1) and O(n) notation. The previous chapters covered how arrays store elements side by side in memory. Here we look at the alternative: a chain of separate objects.
The node-based layout
A linked list stores each element in its own small object called a node. A node holds two things: a value, and a reference to the next node. The list itself is just a reference to the first node, called the head. The last node's next reference is None, which marks the end.
Nodes are allocated one at a time, so they can sit anywhere in memory. Nothing guarantees that node 2 is next to node 1. The only thing connecting them is the next reference.
Building and reading a list
Here is a minimal node class and a function that reads the element at a given position.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def get(head, index):
node = head
for _ in range(index):
if node is None:
break
node = node.next
if node is None:
raise IndexError(index)
return node.value
head = Node(10, Node(20, Node(30)))
print(get(head, 2)) # 30, reached by following 2 links
items = [10, 20, 30]
print(items[2]) # 30, reached by direct index arithmeticThe linked list has no formula that turns an index into an address. To reach index 2, get must start at the head and follow two links. Reaching index i takes i hops, so access by position is O(n). The Python list items is a dynamic array, so items[2] is a direct O(1) lookup.
The loop also checks for None twice. The check inside the loop stops early when the list is too short. The check after the loop catches the case where the index equals the list length exactly.
Insertion: cheap only with the right reference
Linked lists shine at inserting. To put a new node after an existing one, you change two references and nothing else moves.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def insert_after(node, value):
node.next = Node(value, node.next)
head = Node(1, Node(3))
insert_after(head, 2) # O(1): only two references change
items = [1, 3]
items.insert(1, 2) # O(n): later elements shift one slot rightThe new node is created with next pointing at the old successor. Then node.next is redirected to the new node. The work does not depend on the list's length, so it is O(1).
The array version must shift every later element one slot to the right, which is O(n).
Common errors
These mistakes appear often when people first write linked lists:
- Losing the rest of the list. In
insert_after, if you setnode.nextto the new node before saving the oldnode.next, the old successor becomes unreachable. Create the new node with the old successor first, as the code above does. - Forgetting the empty list. An empty list has
head = None. Functions that readhead.nextwithout checking will raiseAttributeError. - Off-by-one in traversal. Moving
indexhops from the head lands on indexindex, notindex + 1. - Assuming O(1) for "insert at position i". Only insertion next to a node you already hold is O(1).
- Creating a cycle by accident. If a node's
nextpoints back to an earlier node, a traversal loop never reachesNoneand runs forever.
How this fits the bigger picture
The linked list trades fast positional access for cheap local changes. Each node also costs extra memory for its reference, and scattered nodes are slower for the CPU to read than a contiguous block. Later chapters cover those costs in detail. For now, remember the core rule: finding a node costs O(n), and changing links around a node you hold costs O(1).
Exercise
A singly linked list has 1,000 nodes. You hold a reference to node number 400 (counting from 0) and want to insert a new value right after it. Then you want to insert another value at index 900 using only the head reference. Compare the cost of the two insertions.
Show answer
The first insertion is O(1): you hold the preceding node, so you only change two references. The second is O(n): you must follow 899 links from the head to reach the node at index 899, then do the O(1) relink. The traversal dominates, so the whole operation is O(n).
Exercise
What goes wrong if insert_after is written as node.next = Node(value); node.next.next = node.next?
Show answer
The old successor is lost. After the first assignment, node.next already points to the new node, so the second assignment makes the new node point to itself. This creates a cycle and drops every later node from the list. The fix is node.next = Node(value, node.next), which saves the old successor before redirecting.