A stack is a linear ADT that operates on the LIFO (Last In, First Out) principle — the most recently added item is the first to be removed. Like a stack of plates.
| Operation | Description | Error condition |
|---|---|---|
| Push | Add an item to the top of the stack | Overflow if full |
| Pop | Remove the item from the top of the stack | Underflow if empty |
| Peek / Top | View the top item without removing it | Underflow if empty |
| isEmpty() | Returns TRUE if stack has no items | — |
| isFull() | Returns TRUE if stack is at capacity | — |
A stack is typically implemented using an array with a stack pointer (SP) that tracks the index of the top item.
// Stack implementation (array-based, max size 5) stack = [_, _, _, _, _] // SP = -1 (empty) Push 10 → SP=0 stack=[10,_,_,_,_] Push 20 → SP=1 stack=[10,20,_,_,_] Push 30 → SP=2 stack=[10,20,30,_,_] Pop → returns 30, SP=1 stack=[10,20,_,_,_] Peek → returns 20, SP unchanged
| Application | Why a stack? |
|---|---|
| Call stack / subroutine calls | Return address and local variables saved on stack; LIFO order means most recent call returned first |
| Undo functionality | Most recent action undone first (LIFO) |
| Reverse Polish Notation (RPN) evaluation | Operands pushed, operators pop and push results |
| Bracket matching | Open brackets pushed, closed brackets matched by popping |
| Browser back button | Pages pushed when visited; popped to go back |
| Depth-first search (DFS) | Nodes pushed onto stack to explore depth-first |
When a subroutine is called, a stack frame is pushed onto the call stack containing the return address, parameters, and local variables. When the subroutine returns, the frame is popped. This links stacks directly to 4.1.1g.
8 questions · instantly marked · AQA 7517 standard
| Term | Definition |
|---|
10 questions · 10 minutes