A stack is a linear data structure that follows LIFO: last in, first out. Push adds an item to the top, pop removes and returns the top item, and peek returns the top item without removing it.
How a stack works
A stack allows access at only one end, called the top. A useful analogy is a stack of plates: the last plate placed on top is the first one removed.
Suppose an empty stack receives these operations:
push("A")produces[A].push("B")produces[A, B].push("C")produces[A, B, C].peek()returnsC, but the stack remains[A, B, C].pop()returns and removesC, leaving[A, B].
This demonstrates LIFO because C, the most recently added item, is removed first.
| Operation | Effect on the stack | Typical result |
|---|---|---|
| Push | Adds an item to the top | Stack size increases by one |
| Pop | Removes and returns the top item | Stack size decreases by one |
| Peek | Returns the top item without removing it | Stack size is unchanged |
Attempting to pop or peek when the stack is empty causes stack underflow. In a fixed-capacity implementation, pushing onto a full stack causes stack overflow. These conditions should be checked before performing the relevant operation.
Stacks are used in function calls, undo features, browser history, depth-first search, and expression evaluation. They may be implemented using an array or a linked list, but their defining feature is LIFO behaviour rather than the underlying implementation.
Exam technique
For an IB Computer Science trace question, draw the stack vertically or write its contents consistently from bottom to top. Show the stack after every operation and distinguish pop() from peek(): a common misconception is that peek removes the top item, but it only reads it.