AQA 7517, section 4.2.3.1
A stack is last in, first out (LIFO). Think of a pile of plates: you add a plate to the top and you take a plate from the top, so the last plate you put on is the first one off.
Items are only ever added to or removed from one end, called the top.
Operations
| Operation | What it does |
|---|---|
push(item) |
Add an item to the top |
pop() |
Remove and return the top item |
peek() (or top) |
Return the top item without removing it |
is_empty() |
True if there are no items |
is_full() |
True if the stack has reached its maximum size |
Starting with an empty stack:
Notice that peek leaves the stack as it was, while pop removes the item.
Underflow and overflow
- Trying to pop from an empty stack is called underflow. Always test with
is_empty()first. - Trying to push onto a full stack (one with a fixed maximum size) is called overflow. Always test with
is_full()first.
Implementing a stack with an array
A stack can be stored in an array, with a pointer that tracks the top item.
- Empty: the pointer is -1 (nothing stored yet).
- Push: if the pointer isn't at the last index, add 1 to it and store the item there.
- Pop: if the pointer isn't -1, read the item at the pointer, then subtract 1 from it.
- Full: the pointer is at the last index of the array.
Popping doesn't need to erase the old value. Moving the pointer down means that slot is treated as empty and will be overwritten by the next push.
class Stack:
def __init__(self, max_size):
self.items = []
self.max_size = max_size
def is_empty(self):
return len(self.items) == 0
def is_full(self):
return len(self.items) == self.max_size
def push(self, item):
if self.is_full():
raise OverflowError("Stack is full")
self.items.append(item)
def pop(self):
if self.is_empty():
raise IndexError("Stack is empty")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("Stack is empty")
return self.items[-1]
Uses
- The call stack, which remembers where to return to after each subroutine call, and why very deep recursion can cause a stack overflow (see 4.1.1.15).
- Undo features and browser back buttons.
- Evaluating expressions, such as converting and calculating Reverse Polish notation.
- Reversing things: push every item, then pop them all off.
- Backtracking, such as searching a maze and returning to the last junction.
Worked example
Task: use a stack to reverse the word "CAT".
word = "CAT"
s = Stack(10)
for letter in word:
s.push(letter)
reversed_word = ""
while not s.is_empty():
reversed_word = reversed_word + s.pop()
print(reversed_word) # TAC
After pushing, the stack from bottom to top holds C, A, T. Popping gives T first, then A, then C, which is the reverse of the order they went in.
Common mistake: mixing up the two orders. Stack means last in, first out. Queue means first in, first out. Say which one you mean, and name the operation, such as pop or dequeue.
Exam tip: for a trace question, draw the stack after every operation, with the top clearly marked. Check for underflow and overflow if the question mentions a maximum size.
Check yourself
An empty stack has these operations applied: push 4, push 9, push 1, pop, pop. What does it contain, and what was returned?
The two pops return 1 and then 9. The stack contains just 4.
What is the difference between pop and peek?
pop removes the top item and returns it. peek returns the top item but leaves it on the stack.
What is stack underflow, and how can you avoid it?
Trying to pop from an empty stack. Test whether the stack is empty before popping.
Give two uses of a stack
Any two of: the call stack for subroutine calls; undo features; browser back button; evaluating expressions; reversing data; backtracking.