Sub topic 7
Two implementations of the same stack
This chapter assumes you know Python classes and exceptions, how a list stores items, how references link objects, and Big-O notation. It also assumes you have read the earlier chapters on the stack specification. You will build two classes that keep the same promise with different internals, and compare them.
One promise, two representations
The stack specification fixes four operations and their behavior:
push(x)addsxto the top.pop()removes and returns the top item.peek()returns the top item without removing it.is_empty()reports whether any items remain.pop()andpeek()raiseIndexErroron an empty stack.
The specification does not say where the items live. That is the freedom you use here. Each implementation picks a representation, which is the concrete data an object holds to stand for the abstract value. Each must make every operation behave as promised.
Here is the interface again, so the code in this chapter runs as one file.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
push(x) then pop() returns x.
pop() and peek() raise IndexError on an empty stack.
"""
@abstractmethod
def push(self, item):
"""Add item to the top of the stack."""
@abstractmethod
def pop(self):
"""Remove and return the top item."""
@abstractmethod
def peek(self):
"""Return the top item without removing it."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""Implementation 1: a list
ListStack stores items in a Python list. It treats the end of the list as the top of the stack.
class ListStack(Stack):
def __init__(self):
self._items = []
def push(self, item):
self._items.append(item)
def pop(self):
if not self._items:
raise IndexError("pop from empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek at empty stack")
return self._items[-1]
def is_empty(self):
return not self._itemsThree choices matter here.
- The top is the end of the list, not the front.
appendandpop()at the end are cheap. Inserting or removing at index 0 shifts every other item. - The class checks for emptiness itself. Python's
list.pop()already raisesIndexError, but with its own message, andself._items[-1]raises a different message. The explicit check makes the error come from the stack's specification rather than from a detail of the representation. - The leading underscore on
_itemsmarks the list as private by convention. Python does not enforce it, so discipline replaces enforcement. A later chapter on representation exposure returns to this.
Implementation 2: a chain of nodes
LinkedStack keeps no list. It keeps a reference to the head node. Each node holds one value and a reference to the node below it. The head is the top of the stack.
class _Node:
def __init__(self, value, next_node):
self.value = value
self.next = next_node
class LinkedStack(Stack):
def __init__(self):
self._head = None
def push(self, item):
self._head = _Node(item, self._head)
def pop(self):
if self._head is None:
raise IndexError("pop from empty stack")
value = self._head.value
self._head = self._head.next
return 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 NoneHere is how the state changes for push(1), push(2), pop().
| Step | `ListStack._items` | `LinkedStack` chain from head |
|---|---|---|
| New stack | `[]` | `None` |
| `push(1)` | `[1]` | `1 -> None` |
| `push(2)` | `[1, 2]` | `2 -> 1 -> None` |
| `pop()` returns 2 | `[1]` | `1 -> None` |
The internal pictures differ, and the sequence of results is identical. The stack is empty when the list is empty, or when the head is None. Those two conditions mean the same abstract thing: no items.
In push, the new node's next_node is the old head, then the head is reassigned to the new node. The order is safe because the right-hand side of the assignment is evaluated before _head changes. In pop, you must read value before moving the head. Otherwise the top item is lost.
Showing they are interchangeable
A function written only against the Stack operations works with either class.
def reverse(items, stack):
for x in items:
stack.push(x)
result = []
while not stack.is_empty():
result.append(stack.pop())
return result
for make_stack in (ListStack, LinkedStack):
print(reverse([1, 2, 3], make_stack()))
# [3, 2, 1]
# [3, 2, 1]Run this after the three class definitions above, in the same file. The loop passes the class itself as a factory, so one line creates a fresh stack of each kind. reverse never touches _items or _head. That is what makes the substitution safe, and a later chapter on client independence develops it.
Checking both against the specification
Two implementations that merely look similar are not enough. You want evidence that each keeps the promise. Write the check once, against the specification, and run it on both.
def check_stack_behavior(make_stack):
s = make_stack()
assert s.is_empty()
s.push(7)
assert not s.is_empty()
assert s.peek() == 7
s.push(9)
assert s.pop() == 9
assert s.pop() == 7
assert s.is_empty()
try:
s.pop()
except IndexError:
pass
else:
raise AssertionError("pop on empty stack must raise IndexError")
check_stack_behavior(ListStack)
check_stack_behavior(LinkedStack)The check covers the push-then-pop rule, the last-in, first-out order, peek leaving the stack unchanged, and the empty-stack error. It says nothing about lists or nodes, so it cannot break when you swap the representation. A third implementation passes or fails the same check.
Comparing the costs
Both stacks give the same results. They differ in cost, and the cost is a property of the implementation, not of the ADT.
| Aspect | `ListStack` | `LinkedStack` |
|---|---|---|
| `push` | O(1) amortized. An occasional append must grow the array, which copies items, so one call can cost O(n). | O(1) every time. It allocates one node. |
| `pop` | O(1) amortized. | O(1). |
| `peek`, `is_empty` | O(1). | O(1). |
| Memory per item | One slot (a reference) in a contiguous array, with spare capacity. | One node object holding two references, plus object overhead. |
| Locality | Items sit next to each other in memory, which tends to be fast on real hardware. | Nodes can be scattered across memory. |
Big-O hides constants. For most programs the list version is both simpler and faster in practice, because Python's list is a heavily optimized built-in. The linked version has a steadier worst-case push, which matters only when a single slow operation is unacceptable. Choose by measuring the workload you have, not by the asymptotic columns alone.
Common errors
- Taking the wrong end of the list. Using
insert(0, item)andpop(0)still gives correct behavior, but each call costs O(n). The behavior check passes, so a test for correctness will not catch it. - Letting Python's own errors leak out. If
ListStack.popjust calledself._items.pop(), it would raiseIndexErrorwith the message "pop from empty list". The type matches the specification, but the message exposes the representation. - Changing the head before reading the value. In
LinkedStack.pop, moving_headfirst loses the item you must return. - Forgetting that
peekmust not mutate. Apeekthat callspopand pushes back works, but breaks if an error occurs between the two steps. - Testing one class only. A check that runs on
ListStackalone says nothing aboutLinkedStack.
Exercise
A teammate adds a method size() to ListStack that returns len(self._items), and a function report(stack) that calls stack.size(). The function works with ListStack but fails with LinkedStack. Which part of the design went wrong, and how do you fix it without changing report?
Show answer
size() was added to one implementation but not to the specification, so report depends on something the interface does not promise. Fix it by adding size to the Stack interface with a stated behavior (it returns the number of items) and implementing it in both classes. For LinkedStack, either walk the chain and count the nodes (O(n)) or keep an integer counter that push increments and pop decrements (O(1), but one more field that must stay correct). Then extend check_stack_behavior to assert the size after each operation. report stays unchanged.