CIE AS & A Level Computer Science, section 10.4 (Introduction to Abstract Data Types (ADT))
Abstract data types
An abstract data type (ADT) is a collection of data together with a set of operations that can be performed on it. The way it is implemented is hidden. A stack, a queue and a linked list are examples.
Stack
A stack is an ADT in which items are added and removed at one end only. It is last in, first out (LIFO): the last item added is the first removed. Think of a pile of plates.
Operations
- Push: add an item to the top.
- Pop: remove and return the item at the top.
- Peek: look at the top item without removing it.
- isEmpty / isFull: test the state.
If you pop an empty stack, underflow occurs. If you push onto a full stack, overflow occurs.
Example
Push 5, push 8, push 2, then pop twice.
| Operation | Stack (top on the right) |
|---|---|
| push 5 | 5 |
| push 8 | 5, 8 |
| push 2 | 5, 8, 2 |
| pop (returns 2) | 5, 8 |
| pop (returns 8) | 5 |
Implementing with an array
A stack of up to 5 items can use an array and a top pointer.
DECLARE Stack : ARRAY[1:5] OF INTEGER
Top ← 0
PROCEDURE Push(Item)
IF Top = 5 THEN
OUTPUT "Stack full"
ELSE
Top ← Top + 1
Stack[Top] ← Item
ENDIF
ENDPROCEDURE
stack = []
stack.append(5); stack.append(8); stack.append(2)
print(stack.pop(), stack.pop(), stack) # 2 8 [5]
Uses
Undo features, the call stack that stores return addresses during function calls, evaluating expressions, and storing register values during an interrupt.
Common mistake: mixing up stacks and queues. A stack is last in, first out; a queue is first in, first out. Also, remember to check for underflow (empty) before a pop and overflow (full) before a push.
Exam tip: show the stack after each operation in a table, and say which end the operations use. Mention the top pointer when describing an array implementation.
Check yourself
What does LIFO mean?
Last in, first out: the last item added is the first removed.
What happens if you pop from an empty stack?
Underflow occurs.
Give one use of a stack.
Any one: undo, the call stack for function calls, or evaluating expressions.