TL;DR
A stack is a collection of items that you can only change at one end, the top. You add an item to the top with a push, and you remove the top item with a pop. Because the last item pushed is always the first one popped, the stack is said to be last in, first out (LIFO). That single rule is enough to solve problems about nesting, undo and deferred work.
Builds on: Array · Leads to: Tree Search · Read with: Queue, Recursion
Where it's used
Undo in editors. Each change you make is pushed onto a stack. Pressing undo pops the most recent change and reverses it, so undo steps go back in exactly the reverse order of your edits.
Function calls in running programs. When a function calls another, the computer saves where to resume and the local variables of the caller on a call stack. When the inner function returns, its data is popped and the caller continues. A recursive call that goes too deep fills this stack, which is the source of the familiar "stack overflow" error.
Calculators that use reverse Polish notation. Expressions such as put operands on a stack and let each operator pop the numbers it needs. Hewlett-Packard calculators used this design from the late 1960s, and it remains a standard example of a stack at work.
How it works
We represent a stack with an array of fixed capacity 3 and a counter top that says how many items are in the stack. Items sit in positions 0 up to top - 1, and the top item is at top - 1.
- Start empty. The stack holds no items, so
top = 0. Check: an empty stack has nothing to pop. - Push 7. Write 7 into position 0 and increase
topto 1. Check: the stack is now[7], and 7 is the top. - Push 4. Write 4 into position 1 and increase
topto 2. Check: the stack is now[7, 4], with 4 on top. - Pop. Read the item at position
top - 1, which is 4, and decreasetopto 1. Check: the stack is[7], and 4 came out first even though 7 went in first. - Push 9. Write 9 into position 1 and set
topto 2. Check: the stack is[7, 9]. - Pop twice. The first pop returns 9 and the second returns 7. Check: the outputs so far are 4, 9, 7. Each pop took the most recent item still in the stack.
- Pop once more. The stack is empty, so
topis 0 and there is nothing to read. Check: this situation is called underflow, and a good implementation reports an error rather than returning garbage.
flowchart TD A[Start: empty stack] --> B[push 7: stack is 7] B --> C[push 4: stack is 7, 4] C --> D[pop returns 4: stack is 7] D --> E[push 9: stack is 7, 9] E --> F[pop returns 9, then pop returns 7] F --> G[pop on empty: underflow error]
The math
A stack is a sequence together with two operations. appends to the end, giving . removes the last element and returns it. The end where both operations act is called the top.
Each symbol in words: is the bottom item and is the top item, and is the current size. The sequence is an ordinary Array viewed through an interface that allows only these two changes.
Step 3 and 4 in symbols (the rule)
The last-in, first-out property says that always returns the element pushed most recently among those not yet popped. Writing the operations as a list, if , then returns , and a second returns . This matches the walkthrough: after pushing 7 and then 4, the first pop returns 4.
Step 6 in symbols (the cost)
A push or pop changes only the top position, so each costs a fixed amount of work whatever the size . Doing pushes and then pops costs about steps in total, which is written . Each single operation is , which is the cost notation explained in Big-O Notation. If the array fills up, a dynamic array copies its contents into a larger one, and that copy happens rarely enough that the average cost per push stays .
Worked examples
Start with an empty stack. Apply these operations in order: push 1, push 2, push 3, pop, pop, peek. Peek returns the top item without removing it.
- push 1: stack is
[1]. - push 2: stack is
[1, 2]. - push 3: stack is
[1, 2, 3]. - pop returns 3. Stack is
[1, 2]. - pop returns 2. Stack is
[1]. - peek returns 1. Stack is still
[1], since peek does not remove.
Interpretation: the pops return the items in reverse order of the pushes. The item 1, pushed first, is the last to come out.
A common task is to check whether brackets in a string are balanced. The method pushes each opening bracket and, on each closing bracket, pops the top and checks that it is the matching opener. Check the string {[()]}.
- Read
{, an opener. Push it. Stack:{. - Read
[, an opener. Push it. Stack:{ [. - Read
(, an opener. Push it. Stack:{ [ (. - Read
), a closer. Pop(, which matches. Stack:{ [. - Read
], a closer. Pop[, which matches. Stack:{. - Read
}, a closer. Pop{, which matches. Stack is empty. - The string ends with an empty stack, so the brackets are balanced.
Now check ([)]. Push (, push [. Read ), pop [. The popped item is not (, so the brackets are not balanced. The check stops at the first mismatch.
Interpretation: the stack remembers which brackets are still open, and the most recent open bracket is the one that must close first. That is exactly the LIFO rule.
Evaluate the reverse Polish expression 5 1 2 + 4 * + 3 -. Each number is pushed. Each operator pops two numbers, applies the operator, and pushes the result. For a subtraction, the first popped number is the right operand.
5: push. Stack:[5].1: push. Stack:[5, 1].2: push. Stack:[5, 1, 2].+: pop 2 and 1, add to get 3, push 3. Stack:[5, 3].4: push. Stack:[5, 3, 4].*: pop 4 and 3, multiply to get 12, push 12. Stack:[5, 12].+: pop 12 and 5, add to get 17, push 17. Stack:[17].3: push. Stack:[17, 3].-: pop 3 (the right operand), then pop 17 (the left), compute , push 14. Stack:[14].- The stack holds one item, 14, which is the result.
Interpretation: no parentheses or precedence rules are needed. The order of the tokens and the stack do all the work. A calculator reads one token at a time, which is why this notation is convenient to build in hardware.
Try it: evaluate 7 2 - 3 *.
Answer: push 7, push 2. The - pops 2 as the right operand and 7 as the left, giving , which is pushed. Push 3. The * pops 3 and 5, multiplies to 15, and pushes 15. The result is 15.
Common mistakes and tradeoffs
It is tempting to think a stack is just a list that can be read anywhere. In fact the point of a stack is that only the top is accessible. Reading the item at the bottom requires popping everything above it, which is the opposite of the direct jump to a position that an Array allows. That restriction is what makes the operations simple and fast, and it is also why a stack is the wrong choice when you need to look up arbitrary items.
It is tempting to think a stack and a queue are interchangeable. In fact a stack is last in, first out and a Queue is first in, first out. Processing tasks in arrival order calls for a queue. Undoing the most recent task calls for a stack.
It is tempting to think pop on an empty stack returns nothing harmlessly. In fact it is an error, called underflow, and code must check for it or the program will read a position that holds no valid item.
When to use it: whenever the newest unfinished item must be handled first, such as nested brackets, undo, depth-first traversal, or deferred work during evaluation. When not to use it: when items must be processed in arrival order, or when you need random access. Alternatives include a Linked List, where push and pop happen at the head without a fixed capacity, and a queue for first-in, first-out work.
History
Translating a formula with nested parentheses into machine instructions means remembering the open groups in order. In the late 1950s, Friedrich Bauer and Klaus Samelson described a "pushdown" store for this job, with the rule that the newest item comes out first. The idea became a standard tool in compilers.
Hardware followed. Most processors keep a call stack in memory, and each function call pushes a new frame onto it. The same structure let Hewlett-Packard build calculators that evaluate reverse Polish notation directly, with the stack visible on screen.
The structure caught on because a single rule covers many problems, and because it is simple enough to implement with a few lines over an array.
Recap
- A stack allows changes only at the top: push adds an item, and pop removes the most recent one.
- Last in, first out: the newest item is always the first one taken out.
- Each operation takes constant time, so n pushes and n pops cost about 2n steps.
- Brackets, undo, function calls and reverse Polish expressions all rely on this one rule.
- Read next: Tree Search, where a stack drives depth-first traversal, and Recursion, where the call stack holds each pending call. The cost claims use Big-O Notation.
Check yourself
QuestionRecall: what does LIFO stand for, and what does it mean for a stack?Show answer
LIFO stands for last in, first out. It means the item most recently pushed is the first one popped, so the order of removal is the reverse of the order of insertion.
QuestionComputation: starting from an empty stack, you push 4, push 8, pop, push 6, pop, pop. What does each pop return, in order?Show answer
Push 4: stack [4]. Push 8: stack [4, 8]. Pop returns 8, stack [4]. Push 6: stack [4, 6]. Pop returns 6, stack [4]. Pop returns 4, stack empty. The pops return 8, 6, 4.
QuestionWhy: why does bracket matching need a stack rather than just a count of open brackets?Show answer
A count tells you how many brackets are open but not which kind, or in what order. Matching ([)] needs the most recent opener to close first, and the stack keeps the open brackets in order so that each closer can be compared with the correct opener. A count would wrongly accept ([)] if the total numbers matched.
QuestionApplied: a program needs to process print jobs in the order they arrived. Would you use a stack? Explain.Show answer
No. A stack would print the most recently arrived job first, so early jobs could wait indefinitely. Jobs that must be handled in arrival order need a queue, which is first in, first out.
Sources
- Wikipedia, "Stack (abstract data type)": https://en.wikipedia.org/wiki/Stack_(abstract_data_type)
- Wikipedia, "Reverse Polish notation": https://en.wikipedia.org/wiki/Reverse_Polish_notation