Sub topic 5
Implementing a stack with a linked list
This chapter assumes you have read the array-backed stack chapter and know Python classes, references, and Big-O notation. Here you build the same stack interface on a singly linked list.
The idea
A singly linked list is a chain of nodes. Each node holds a value and a reference to the next node. The stack keeps one reference, _head, which points at the top of the stack.
Pushing adds a new node in front of the head. Popping removes the head node. Both operations touch only the head, so neither one walks the list.
The implementation
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
class LinkedStack:
def __init__(self):
self._head = None
self._size = 0
def push(self, value):
self._head = _Node(value, self._head)
self._size += 1
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
node = self._head
self._head = node.next
self._size -= 1
return node.value
def peek(self):
if self._head is None:
raise IndexError("peek at empty stack")
return self._head.value
def is_empty(self):
return self._head is None
def __len__(self):
return self._size
stack = LinkedStack()
for n in (1, 2, 3):
stack.push(n)
print(stack.pop()) # 3
print(stack.peek()) # 2
print(len(stack)) # 2The class uses _Node(value, self._head) to build the new node so that it already points at the old top. Only then does _head move to the new node. The order matters, as the next section shows.
Why the order of steps matters
In push, the new node must take the old head as its next before _head is reassigned. If you reassign _head first, you lose the only reference to the rest of the stack. Everything below the new node becomes unreachable.
In pop, save the head node in a local variable before moving _head. Otherwise you have nothing to read the value from.
Costs compared with the array stack
| Property | Array-backed | Linked-list |
|---|---|---|
| push | Amortized O(1), occasional O(n) resize | O(1) worst case |
| pop, peek, is_empty | O(1) | O(1) |
| Memory per item | One slot | One node object plus one reference |
| Memory locality | Contiguous | Scattered across the heap |
| Resizing | Needed | Never |
The linked version has a stronger guarantee on each push, because it never copies items. In practice, though, the array version is usually faster in Python. A list stores its items in one block, which is friendlier to the CPU cache, and allocating one node object per push is expensive.
Choose the linked version when you need a hard O(1) bound on every operation, or when you are learning how pointer-based structures work. Choose the list for everyday code.
Common errors
- Forgetting to decrement
_sizeinpop, solendrifts from the real count. - Returning the node instead of
node.value, which leaks the internal type to callers. - Skipping the empty check, which gives an unhelpful
AttributeErroronNoneinstead of a clearIndexError.
Exercise
In LinkedStack.push, what goes wrong if you write self._head = _Node(value, None) instead of passing self._head?
Show answer
The new node no longer points at the old top, so every earlier item becomes unreachable. After one push the stack holds only the newest value, while _size still counts the lost items.
Exercise
Why is LinkedStack.push O(1) in the worst case, while Stack.push on a list is only amortized O(1)?
Show answer
The linked version allocates one node and changes two references, regardless of stack size. The list version occasionally has to allocate a larger block and copy every item, which costs O(n) on that single push.