Sub topic 2
Building a Singly Linked List
Prerequisites
This chapter assumes you can write Python classes and loops, and that you know a variable holds a reference to an object rather than a copy of it. It also assumes you can read introductory Big-O notation such as O(1) and O(n). The previous chapter introduced nodes and references. Here you combine them into a working list class.
The working model
A singly linked list is a chain of node objects. Each node stores one value and one reference to the next node. The list object itself stores a single reference, called the head, which points at the first node.
Four facts describe the whole structure:
- The head is the only entry point. Every other node is reachable only by following
nextreferences from the head. - The last node has
nextset toNone. That is how a walk knows to stop. - An empty list has
headset toNone. - Nodes are independent objects. They can sit anywhere in memory, and nothing about their position says which comes first. Only the references define the order.
The Node class
The node is small. It needs a value and a next field, and the constructor lets you set next at creation time.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = nextThe parameter name next shadows Python's built-in next() function inside __init__. This is harmless here because the constructor never calls the built-in. The attribute self.next is the conventional name and is used throughout this tutorial.
You can wire nodes by hand to see that the structure is only references:
a = Node(1)
b = Node(2)
a.next = b
print(a.next is b) # True: the same object, not a copy
print(a.next.value) # 2
print(b.next is None) # True: b is the last nodeHere a is effectively the head of a two-node list. Nothing but a.next connects the two nodes. If you reassign a.next, the link is gone.
The list class
Writing a.next = b by hand does not scale, and it leaves the head implicit. A LinkedList class makes the head explicit and gives you a place to put operations.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def push_front(self, value):
self.head = Node(value, self.head)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
items = LinkedList()
for v in (3, 2, 1):
items.push_front(v)
print(list(items)) # [1, 2, 3]The loop pushes 3, then 2, then 1, and each push goes to the front. The final order is therefore 1, 2, 3.
How push_front works
The single line self.head = Node(value, self.head) does two things in a fixed order:
- The right side runs first. It creates a new node whose
nextis the current head. The old chain is now attached behind the new node. - The assignment runs second. It makes
headpoint at the new node.
The order is what makes this safe. Python evaluates the right side before it rebinds self.head, so the old head is captured before it is replaced. The operation touches a fixed number of references no matter how long the list is, so it costs O(1).
The most common mistake is to write self.head = Node(value) instead. That creates a one-node list and discards the old head. Nothing else refers to the old chain, so Python's garbage collector reclaims it, and the data is gone.
How iteration works
__iter__ is a generator. It starts at the head, yields each value, and moves to current.next. It stops when current becomes None. Because the class defines __iter__, list(items), for v in items, sum(items) and max(items) all work without extra code.
The loop condition is current is not None. This is deliberate. Using current.next is not None would stop one node early and would crash on an empty list, because None has no next attribute.
Making the class easier to use
A list you cannot print or measure is awkward to debug. This version adds a constructor that accepts initial values, an emptiness check, a length, and a readable representation.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
class LinkedList:
def __init__(self, values=()):
self.head = None
for v in reversed(list(values)):
self.push_front(v)
def is_empty(self):
return self.head is None
def push_front(self, value):
self.head = Node(value, self.head)
def __iter__(self):
current = self.head
while current is not None:
yield current.value
current = current.next
def __len__(self):
return sum(1 for _ in self)
def __repr__(self):
return "LinkedList([" + ", ".join(repr(v) for v in self) + "])"
items = LinkedList([1, 2, 3])
print(items) # LinkedList([1, 2, 3])
print(len(items)) # 3
print(items.is_empty()) # False
print(LinkedList().is_empty()) # TrueThe constructor reverses its input and pushes each value to the front. That keeps the original order while using only push_front, which is already known to be O(1) per value.
__len__ walks the whole list, so it costs O(n). A list can instead keep a size attribute that every insertion and deletion updates, which makes len() O(1). The cost is one more thing to keep correct in every method. For this chapter the O(n) version keeps the class small.
Costs of what you have built
| Operation | Cost | Reason |
|---|---|---|
| `is_empty()` | O(1) | One comparison with `None` |
| `push_front(value)` | O(1) | Fixed number of reference changes |
| Iterate over all values | O(n) | One step per node |
| `len(items)` | O(n) | Walks every node |
| Read the first value | O(1) | `items.head.value` |
| Read the value at index k | O(k) | Must follow k references from the head |
The last row is the main difference from an array, where indexing is O(1). The next chapters build on this table.
Common errors
- Dereferencing
None.AttributeError: 'NoneType' object has no attribute 'next'means your code followed a reference past the last node, or started on an empty list. Check the loop condition and handlehead is Noneexplicitly. - Losing the head. Assigning to
self.headbefore saving the old value discards the rest of the list. Always attach the old chain to something before you overwrite the reference to it. - Comparing with
==instead ofis. Useis Noneandis not None. A class can define__eq__in a way that makes== Nonemisleading, andisstates the intent. - Creating a cycle by accident. If a node's
nextpoints back to an earlier node,__iter__never reachesNoneand loops forever. Cycle detection is covered in a later chapter. - Sharing nodes between lists. If two lists contain the same node object, changing one list changes the other. Create new
Nodeobjects when you copy values.
Verifying the structure
When a list behaves strangely, inspect the nodes directly rather than guessing. This short check walks the chain and prints each node's value next to the value it points to:
current = items.head
while current is not None:
following = current.next.value if current.next is not None else None
print(current.value, "->", following)
current = current.nextFor the list [1, 2, 3] it prints 1 -> 2, 2 -> 3 and 3 -> None. If any line is missing or repeats, a next reference is wrong. This check is more reliable than reading the generator's output alone, because it shows the links themselves.
Exercises
Exercise
After running head = Node(1) and then head = Node(2, head), what does head.next.value return, and what happens if you instead write head = Node(2) for the second line?
Show answer
With Node(2, head), the new node's next is the old node, so head.next.value is 1. With head = Node(2), the new node's next is None, so head.next.value raises AttributeError. The old node is no longer referenced anywhere and is garbage collected.
Exercise
Add an is_empty-style method named first() to the LinkedList class that returns the first value, or None if the list is empty. What is its time cost, and why does it need a check before reading self.head.value?
Show answer
The method is def first(self): return None if self.head is None else self.head.value. It costs O(1), because it reads one reference and one field regardless of list length. The check is needed because an empty list has head set to None, and reading .value on None raises AttributeError.