Sub topic 1
Nodes and References: The Building Block
Prerequisites
This chapter assumes you can read basic Python: variables, loops, conditionals, functions, and classes with fields. You should also know Big-O notation at an introductory level, such as the difference between O(1) and O(n). You don't need any earlier knowledge of linked lists.
Why start with a single node
A linked list stores a sequence as many small separate objects instead of one block of memory. Each object is a node. The nodes are joined by references. Every linked list operation in later chapters is built from these two ideas, so it pays to understand them well first.
A node is an object with two fields:
- A value, which is the data you want to store.
- A next reference, which points to another node or to nothing.
A reference is a value that tells the program where another object lives. In Python, every variable holds a reference to an object. When you write b = a, no object is copied. Both names refer to the same object.
Writing a node in Python
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
a = Node("a")
b = Node("b")
a.next = b
print(a.value) # a
print(a.next.value) # b
print(b.next) # NoneThe line a.next = b is the only thing that connects the two nodes. Neither node knows how many nodes exist in total. Each one knows only its direct successor.
None is Python's way of saying "no object here". A node whose next is None is the last node in its chain. Code that walks a chain uses this as the stopping signal.
How the chain looks in memory
The variable head is not a node. It is a reference to the first node. The list as a whole is just that one reference. If you lose it and nothing else refers to the first node, Python's garbage collector can reclaim the nodes, and the data is gone.
Building a chain by hand
You can build the chain from the diagram without any list class:
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
head = Node(1, Node(2, Node(3)))
current = head
while current is not None:
print(current.value)
current = current.nextThis prints 1, 2, 3. The loop moves current along the chain, one reference at a time. It is the pattern behind traversal, which a later chapter covers in full.
Reference behavior to keep in mind
Three facts about references explain most beginner bugs.
- Assignment copies the reference, not the node. After
current = head, both names point to the same node. Changingcurrent.valuealso changeshead.value. - Reassigning a name does not change the node. The statement
current = current.nextmoves the namecurrent. The nodes stay where they are. - Changing
.nextrewires the chain. The statementa.next = cchanges which node followsa. Any node that was only reachable through the old link may become unreachable.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
first = Node("x")
alias = first
alias.value = "y"
print(first.value) # y
alias = Node("z") # alias now names a different node
print(first.value) # yThe first assignment to alias.value changes the shared node. The second assignment to alias only moves the name.
Common errors
- Following
nextonNone. Writingcurrent.next.valuewhencurrent.nextisNoneraisesAttributeError. Checkis not Nonebefore you step forward. - Losing the rest of the chain. If you set
a.next = cbefore saving the olda.next, the nodes afteraare no longer reachable. - Comparing with
==instead ofis. Useis Noneandis not Noneto test for the end of a chain.
Exercise
Exercise
Given head = Node(1, Node(2, Node(3))), what does head.next.next.value evaluate to, and what happens if you evaluate head.next.next.next.value?
Show answer
head.next.next.value is 3, because it follows two next references to the third node. head.next.next.next is None, so reading .value on it raises an AttributeError.