Building a stack class
After this: Read a stack class, and say why push and pop are fast.
On this page · 6 sections · 2 checks
In the last lesson you pushed and popped with plain lines of code. That shows the idea, but a program should not have to repeat those lines every time it needs a stack. This lesson puts them in one place, then asks how fast they are.
The stack as a class
A class is a way to keep data together with the functions that use it. With a class, you can write s.push(1) and s.pop(), and the class looks after top for you.
The plain lines ignored two problems: the row can be full when you push, and the stack can be empty when you pop. The class deals with both.
class ArrayStack: def __init__(self, capacity=4): self.cells = [None] * capacity self.top = 0 # index of the next free cell; also the size
def push(self, value): if self.top == len(self.cells): self.cells.extend([None] * len(self.cells)) # grow like a dynamic array self.cells[self.top] = value self.top += 1
def pop(self): if self.top == 0: raise IndexError("pop from an empty stack") self.top -= 1 value = self.cells[self.top] self.cells[self.top] = None return value
def peek(self): return self.cells[self.top - 1]public class ArrayStack { int[] cells = new int[4]; int top = 0; // index of the next free cell; also the size
void push(int value) { if (top == cells.length) cells = java.util.Arrays.copyOf(cells, cells.length * 2); // grow like a dynamic array cells[top] = value; top++; }
int pop() { if (top == 0) throw new RuntimeException("pop from an empty stack"); top--; int value = cells[top]; cells[top] = 0; return value; }
int peek() { return cells[top - 1]; }}Here is how to read it.
cellsis the row of cells, andtopis the number you already know.pushfirst checks whether the row is full. If it is, the row doubles in size. Then come the same two lines as before.popis highlighted. It first checks whether the stack is empty, because then there is nothing to give back. Then come the same three lines as before.peekshows the top value without removing it. This small version assumes that the stack is not empty.
Why push and pop are fast
Each push and each pop touches one cell. No other cell is looked at, and no value moves. The stack could hold three values or a million, and the work would be the same.
A cost like this is written O(1), which means the number of steps stays the same when the data grows. The lesson Counting steps explains O(1) and O(n).
When the row is full
One case costs more. Take a stack of four cells that holds 1, 2, 3 and 4, and push 5.
- The row is full, so it grows to eight cells.
- The four values are copied across.
- 5 is written at index 4, and
topbecomes 5.
You saw this growing step in Appending and the full row. That one push is O(n), which means the work grows with the size of the stack.
It happens rarely, so the cost per push stays constant on average over many pushes. That average is called amortized O(1), and Why appending stays fast shows where it comes from. Our pop never copies anything, so pop is always O(1).
Watch it happen
Push five values onto a stack of four cells, then pop. Watch what the fifth push has to do.
- Push 1Push 1. There is room, so this writes one cell.
- Push 2
- Push 3
- Push 4
- Push 5
- Pop
- 3·
- 2·
- 1·
- 0·
Run an operation to begin.
The first four pushes wrote one cell each. The fifth copied four values before it wrote its own. The pop touched one cell.
Check yourself
A stack holds a million numbers. Why are push and pop still O(1)?
This program uses the class from this lesson. What do the two print lines show?
s = ArrayStack()s.push(1)s.push(2)s.push(3)print(s.pop()) # 3: the last one ins.push(4)print(s.pop(), s.pop(), s.top)ArrayStack s = new ArrayStack();s.push(1);s.push(2);s.push(3);System.out.println(s.pop()); // 3: the last one ins.push(4);System.out.println(s.pop() + " " + s.pop() + " " + s.top);Connect
- Read a stack class, including its two safety checks: a full row and an empty stack.
- Say why push and pop are O(1): each touches one cell and no value moves.
- Say what happens on a push into a full row, and why push is still amortized O(1).