Sub topic 1
Starting point: what a singly linked list cannot do well
Prerequisites
This chapter assumes you know:
- Basic Python: classes, methods, and generators.
- How a singly linked list stores nodes, each holding a value and a
nextreference. - Big-O notation for time complexity.
- That a reference can be
None, and thatiscompares object identity.
The structure we start from
A singly linked list is a chain of nodes. Each node knows only the node after it. The list object keeps a head reference to the first node. Many implementations also keep a tail reference to the last node.
Here is a minimal version with head and tail. It supports appending in constant time and removing a node you already hold.
class Node:
def __init__(self, value):
self.value = value
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def push_back(self, value):
node = Node(value)
if self.tail is None:
self.head = node
else:
self.tail.next = node
self.tail = node
return node
def remove(self, node):
prev = None
cur = self.head
while cur is not None and cur is not node:
prev = cur
cur = cur.next
if cur is None:
raise ValueError("node is not in this list")
if prev is None:
self.head = node.next
else:
prev.next = node.next
if node is self.tail:
self.tail = prev
node.next = None
def __iter__(self):
node = self.head
while node is not None:
yield node.value
node = node.next
lst = SinglyLinkedList()
for v in (1, 2, 3):
lst.push_back(v)
last = lst.push_back(4)
lst.remove(last)
print(list(lst)) # [1, 2, 3]Appending is O(1) because tail gives direct access to the end. The interesting part is remove.
Where it falls short
Removal needs the predecessor
To unlink a node, you must change the next of the node before it. A singly linked node has no reference to that predecessor. The while loop in remove therefore walks from head until it finds it. Even though the caller already holds node, the cost is O(n).
Removing the last node is O(n)
A tail reference does not fix this. After removing the tail, the new tail is the node before it, and you can only reach that node by walking from the head. Adding at the end is O(1), but removing from the end is O(n). That makes a singly linked list a poor fit for a double-ended queue.
Traversal runs in one direction
Nothing lets you step from a node to its predecessor. To read the list backward, you must collect the nodes first, for example into a Python list. You can also use recursion, which risks hitting the recursion limit on long lists. Both approaches cost O(n) extra memory.
Empty and one-element cases need branches
Look at push_back and remove. Each has an if for an empty list, for the head, or for the tail. Every operation must keep head and tail consistent with each other. Forgetting one of these branches is the most common source of bugs in list code. For example, after removing the only node, head becomes None but a stale tail can survive.
What the next chapters change
The two variants in this tutorial each target some of these weaknesses.
| Weakness | Fixed by |
|---|---|
| Removal needs the predecessor | Adding a `prev` pointer (doubly linked) |
| Removing the tail is O(n) | Adding a `prev` pointer |
| Backward traversal is impossible | Adding a `prev` pointer |
| Special cases at the ends | Sentinel nodes |
| Wrapping around, as in a cycle of tasks | Linking the tail back to the head (circular) |
The cost is extra memory per node and more pointers to keep consistent on every change. Later chapters measure that trade-off.
Exercise
A singly linked list keeps both head and tail references. You hold a reference to a node in the middle. Why is removing that node O(n), and why is removing the tail node also O(n)?
Show answer
In both cases the node before the target must have its next reference changed, and a singly linked node does not store its predecessor. You find that predecessor by walking from the head, which takes O(n) in the worst case. The tail reference gives fast access to the last node but not to the node before it. After removing the tail, that earlier node must become the new tail, so you still have to walk the list to find it.