Sub topic 1
Nodes and references: the building block
A linked list is a sequence built from small separate objects that point to each other. Before you can write insertion, deletion, or reversal, you need a precise picture of what one of those objects holds and what "points to" means in your language. This chapter builds that picture in Python.
Prerequisites
This chapter assumes you already know:
- Basic Python: variables, loops, conditionals, and functions.
- How to define a class with an
__init__method and fields. - Introductory Big-O notation, such as the difference between O(1) and O(n).
You do not need to have seen a linked list before.
What a node is
A node is a small object with two parts:
- A value, which is the data you want to store.
- A reference to the next node, or
Noneif there is no next node.
A reference is a handle that lets you reach another object. In Python, every variable and every attribute holds a reference to an object, not the object itself. A node's next attribute therefore needs no special pointer feature. It is an ordinary attribute that happens to hold another Node.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = nextTwo details matter here:
nextis a parameter name that shadows the built-innext()function inside__init__. This is harmless in this class, and it is the conventional name in linked list code. If you also call the built-innext()in the same scope, pick another name.next=Nonemakes the reference optional. A node created alone does not point anywhere.
Connecting nodes by hand
You can build a three-node chain without any list class. Create the nodes, then assign each next attribute.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
a = Node(1)
b = Node(2)
c = Node(3)
a.next = b
b.next = c
print(a.value) # 1
print(a.next.value) # 2
print(a.next.next.value) # 3
print(a.next.next.next) # NoneReading a.next.next.value follows two references from a, one at a time. The chain ends at c, whose next is still None.
The diagram shows the same structure. Each box is a node, and each arrow is a reference stored in the next attribute.
The nodes do not need to sit next to each other in memory. The order of the sequence lives in the references, not in the addresses of the objects. This is the main difference from an array, and a later chapter covers its consequences.
Names, objects, and aliasing
A variable name such as a is a label bound to an object. Assigning one variable to another copies the reference, not the node.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
a = Node(1)
b = Node(2)
a.next = b
x = a # x and a refer to the same node
x.value = 10 # change the node through x
print(a.value) # 10
x = b # rebind x; the node that a refers to is untouched
print(a.value) # 10
print(x is b) # TrueThe two kinds of assignment behave differently:
| Statement | What it does | Effect on the list |
|---|---|---|
| `x.value = 10` | Changes an attribute of the node `x` refers to | The node changes, so every name that refers to it sees the change |
| `x = b` | Makes the name `x` refer to a different node | No node changes |
| `x.next = b` | Changes which node follows the one `x` refers to | The structure of the list changes |
Almost every linked list bug comes from mixing these up. Moving a traversal variable, as in current = current.next, is safe because it only rebinds a local name. Assigning to .next rewires the list.
Use is to compare node identity and == to compare values. Two different nodes can hold equal values, and a is b is still False for them.
None marks the end
None is Python's "no object" value. In a linked list it has a job: a node whose next is None is the last node. Every traversal loop depends on this convention.
def count_nodes(head):
count = 0
current = head
while current is not None:
count += 1
current = current.next
return count
a = Node(1, Node(2, Node(3)))
print(count_nodes(a)) # 3
print(count_nodes(None)) # 0This example uses the Node class defined above. Passing Node objects as next builds the chain from the inside out, so Node(1, Node(2, Node(3))) is the same three-node chain as before.
Note that the empty list is just None. count_nodes(None) returns 0 without any special case, because the loop condition is false on the first check.
Test for the end with is not None rather than a bare while current:. A node object is truthy by default, so the bare form works today. It breaks if someone later adds __len__ or __bool__ to Node, and it hides your intent.
Holding on to the head
A chain of nodes has no container. The only way to reach the whole chain is a reference to its first node, called the head. If you lose the head, you lose the list.
a = Node(1, Node(2, Node(3)))
a = None # the only reference to the first node is goneAfter this assignment nothing refers to the node holding 1. Python's garbage collector can reclaim it. Reference counting then drops the count for the node holding 2, and so on down the chain. The whole list disappears.
The same thing happens on a smaller scale when you rewire a link carelessly:
a = Node(1, Node(2, Node(3)))
# Wrong: the node holding 2 is now unreachable, and so is the node holding 3
a.next = NoneBefore overwriting any .next, ask whether another reference to the old target exists. If not, save it in a variable first. Insertion and deletion in later chapters depend on this habit.
Common errors
These mistakes appear again and again when people write their first node code.
- Calling
.nextonNone. An expression likecurrent.next.nextraisesAttributeError: 'NoneType' object has no attribute 'next'when the chain is shorter than you assumed. Checkcurrent.next is not Nonebefore looking two steps ahead. - Moving the head. Writing
head = head.nextinside a traversal loses the first node for good. Copy it first withcurrent = headand movecurrent. - Overwriting before saving. Setting
current.next = somethingbefore you save the oldcurrent.nextloses the rest of the chain. - Accidental cycles. If a node ends up reachable from itself, a traversal loop never reaches
Noneand runs forever. A later chapter covers detecting this on purpose. - Using a mutable default. A default such as
next=[]ornext=Node(0)is created once and shared by every call. KeepNoneas the default.
Cost of the model
Each node is a separate Python object with its own attribute storage. That has three consequences:
- Memory use is higher than for a list of the same values, because each element carries a node object plus one reference.
- Reaching the k-th node takes k steps, because you must follow k references from the head. Indexing is O(n), not O(1).
- Changing the link between two nodes is O(1) once you hold a reference to the node, because it assigns one attribute and moves no data.
The last point is why the structure exists. You have not yet seen how to find the right node cheaply, and later chapters return to that trade-off.
The next chapter wraps the head in a LinkedList class so that callers do not handle raw nodes.
Exercise
Given a = Node(1, Node(2, Node(3))) and x = a.next, you run x.next = None. What does count_nodes(a) return, and why?
Show answer
It returns 2. The name x refers to the node holding 2, which is the same object as a.next. Setting x.next = None changes that node's attribute, so the chain is now 1, then 2, then None. The node holding 3 is no longer reachable and can be garbage collected.
Exercise
A student writes a loop to count nodes, but uses head = head.next instead of a separate current variable. The function returns the right count. Why is it still a problem if the caller wants to keep using the list afterward?
Show answer
The loop rebinds only the function's local name head, so the caller's own variable still refers to the first node and the list is intact. The version is therefore correct for this function. The real risk is in code that stores the head on an object, for example self.head = self.head.next. That change overwrites the only reference to the first node and loses it. Use a separate current variable to stay safe in both cases.