Sub topic 2
Building a Singly Linked List
This chapter assumes you know Python classes, loops, and introductory Big-O notation. You should also know that Python variables hold references to objects, not copies of them.
The idea
The previous chapter introduced the node: an object that holds a value and a reference to another node. A singly linked list is a chain of such nodes. Each node points forward to the next one, and the last node's next is None.
The list object itself stores only one thing: a reference to the first node, called the head. Every other node is reachable only by following next references from the head. If you lose the head, you lose the whole list.
The node and the list class
Here is the minimal implementation. The next default of None lets you create a lone node.
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]An empty list is simply head = None. There is no size field, no array, and no preallocated capacity.
How `push_front` works
The line self.head = Node(value, self.head) does two things in one expression. Python first evaluates the right side. It creates a new node whose next is the current head. Only then does it assign the new node to self.head.
Trace the loop above:
- Push 3: the list is
3. - Push 2: the new node points to the old head (3), so the list is
2 -> 3. - Push 1: the list is
1 -> 2 -> 3.
The order of the arguments matters. If you set self.head before reading it, you lose the old chain. Always connect the new node to the existing list first, then move the head.
push_front takes O(1) time. It touches only the new node and the head, whatever the list's length.
How `__iter__` works
Because __iter__ is a generator, list(items) and for v in items both work. The method starts at the head and yields each value. It then moves to current.next. It stops when current becomes None.
This is the basic traversal pattern. Almost every linked list operation is a variation of it: start at the head, test for None, and advance.
Common errors
- Dropping the old head. Assigning
self.head = Node(value)and attaching the old head afterward loses the chain. Build the new node'snextfirst. - Dereferencing
None. Writingcurrent.next.nextwhencurrent.nextisNoneraisesAttributeError. Check each reference before you follow it. - Testing truthiness. Use
current is not None, notwhile current. It states the intent exactly, and it keeps working if you later add__bool__or__len__to your classes. - Infinite loops. If a bug creates a cycle, a traversal never reaches
None. A later chapter covers detecting this.
Cost summary
| Operation | Time | Why |
|---|---|---|
| `push_front` | O(1) | Only the head changes |
| Traversal | O(n) | Each node is visited once |
| Access by index | O(n) | You must walk from the head |
Only the first node is reachable in constant time. That limitation drives most of the design choices in the chapters that follow.
Exercise
In push_front, why does Node(value, self.head) need to be evaluated before the assignment to self.head, and what would happen if you wrote self.head = Node(value) followed by self.head.next = self.head?
Show answer
Python evaluates the right side first, so the new node captures the old head in its next before self.head changes. In the alternative, self.head = Node(value) overwrites the head, so the old chain is no longer referenced. Then self.head.next = self.head makes the new node point to itself, which creates a one-node cycle. The original nodes are lost, and any traversal loops forever.
Exercise
Write a method __len__ for LinkedList that returns the number of nodes. What is its time complexity?
Show answer
def _len_(self): count = 0; current = self.head; while current is not None: count += 1; current = current.next; return count. It is O(n) because it must visit every node. Storing a size field that is updated on each insertion and deletion would make it O(1).