Stacks
A stack adds and removes items at the same end, called the top. The last item added is the first one removed.
Simple example
Push 2, then 5, then 8. Pop once and print the value that came off the top.
#include <iostream>
int main() {
int stack[] = {0, 0, 0};
int items[] = {2, 5, 8};
int size = 0;
while (size < 3) {
stack[size] = items[size];
size += 1;
}
size -= 1;
std::cout << stack[size] << '\n';
}
8
Everyday examples
Lift the top workbook
Workbooks 12, 17 and 21 land on a desk in that order. Which can you lift without moving another book?
Book 21 is on top. Lifting it exposes 17.
Undo a drawing
A learner draws a circle, adds a line, then adds a dot. Undo twice. What is left?
Pop the dot first and the line second. The circle was the earliest change and remains.
Retrace a walk
You visited rooms 4, 6 and 9. Log each room as you enter. If you leave 9 and retrace one step, where are you?
Remove the current room from the stack. Room 6 is now on top.
Cost and limits
Check for an empty stack before popping. A linked stack can push or pop in constant time. A growing array occasionally resizes.