What is a Stack
A stack is a collection that enforces a single rule: the last element added is the first one removed. This is called LIFO (Last In, First Out).
Think of a stack of plates. You place new plates on top. You take plates from the top. To reach the plate at the bottom, you must first remove every plate above it.
The plates analogy
Imagine stacking plates after washing them. Each new plate goes on top. When you need a plate, you grab the one on top. You never slide a plate out from the middle; you always work from the top down.
In a stack, too, the most recently added element is always the first one available.
Unlike arrays and linked lists, a stack doesn't give you access to any arbitrary element. It only exposes one end, the top, and you interact with it through exactly three operations.
That's because a stack is an abstract data type (ADT). It defines what operations are allowed and what rules they follow, but says nothing about how the data is stored in memory. Arrays and linked lists are concrete data structures: they describe a specific memory layout. The stack's rules work as a contract, and you can honor it with an array, a linked list, or anything else that supports push and pop with LIFO semantics.
The three operations
A stack's entire interface is three operations:
- push: add an element to the top
- pop: remove the element from the top
- peek: read the top element without removing it
There is no indexing, no search and no insertion in the middle. To reach anything below the top, you pop what's above it.
push: adding to the top
push places a new element on top of the stack. Every push increases the stack's size by one.
99 lands on top, and 42 stays out of reach until 99 is removed
This is , because it always writes to the same place.
pop: removing from the top
pop removes the top element and returns it. The element below it becomes the new top.
99 is removed, and 42 is the top again
Also , for the same reason: it always removes from the same place.
peek: looking without touching
peek (sometimes called top) returns the top element without removing it. Use it when you need to check what's on top before deciding whether to pop. After push(42), push(17) and push(8), a peek returns 8 and leaves the stack as it was:
8 is read and stays on top, nothing is written and top doesn't move
peek is also .
Array-based implementation
The simplest way to implement a stack is with a fixed-size array and an index that tracks the top.
#define MAX 100struct Stack { int data[MAX]; int top;};void stack_init(struct Stack *s) { s->top = -1; // -1 means empty}int stack_is_empty(struct Stack *s) { return s->top == -1;}int stack_is_full(struct Stack *s) { return s->top == MAX - 1;}The top index starts at -1. Each push increments it before writing; each pop reads then decrements it.
void push(struct Stack *s, int value) { if (stack_is_full(s)) return; // stack overflow s->data[++s->top] = value;}int pop(struct Stack *s) { if (stack_is_empty(s)) return -1; // stack underflow return s->data[s->top--];}int peek(struct Stack *s) { if (stack_is_empty(s)) return -1; return s->data[s->top];}The array implementation is cache-friendly and has no allocation overhead. The tradeoff is the fixed upper bound: you must know the maximum stack size in advance.
Linked-list-based implementation
A linked list removes the fixed-size constraint. The head of the list becomes the top of the stack, so push and pop both operate at the head, which is O(1) in a linked list.
struct Node { int value; struct Node *next;};struct Stack { struct Node *top;};void stack_init(struct Stack *s) { s->top = NULL;}void push(struct Stack *s, int value) { struct Node *node = malloc(sizeof(struct Node)); node->value = value; node->next = s->top; s->top = node;}int pop(struct Stack *s) { if (s->top == NULL) return -1; struct Node *temp = s->top; int value = temp->value; s->top = s->top->next; free(temp); return value;}int peek(struct Stack *s) { if (s->top == NULL) return -1; return s->top->value;}The linked-list stack grows without a predefined limit. Each push allocates one node; each pop frees it.
How the two implementations compare:
| Array-based | Linked-list-based | |
|---|---|---|
| Max size | Fixed at creation | Unlimited |
| Memory | Compact, cache-friendly | Scattered, pointer overhead |
| Overflow risk | Yes (bounded) | Only if memory is exhausted |
| Allocation | None (pre-allocated) | One malloc per push |
For small, bounded stacks, like a function call stack or an expression evaluator, the array version is simpler and faster. For unbounded stacks where the maximum depth is unknown, use the linked list.
Growing without a limit
Ideally, a stack has no ceiling at all, so the code that pushes never needs to know how deep it will go. The linked list gets there, but it pays one malloc per push and scatters its nodes through memory. Most standard libraries take a third path: an array that grows when it fills up.
struct Stack { int *data; int top; int capacity;};int push(struct Stack *s, int value) { if (s->top == s->capacity - 1) { int *grown = realloc(s->data, 2 * s->capacity * sizeof(int)); // out of memory: the old array is intact if (grown == NULL) return 0; s->data = grown; s->capacity *= 2; } s->data[++s->top] = value; return 1;}When top reaches the last slot, push asks for an array twice as large and realloc copies the old values into it. That copy costs O(n), but it only happens when the capacity doubles: after copying n values, the next n pushes go straight into free slots. Spread over all of them, push stays , the same reasoning as dynamic arrays in the Arrays article. pop and peek don't change, and the values stay contiguous, so the stack keeps the cache behavior of the fixed array.
In the chart, each bar is one push, starting from a capacity of 1. Most bars cost a single write; the spikes are the pushes that found the array full and copied everything before writing. The spikes double in height, but they also get twice as far apart, so the average line flattens out at about 3 operations per push.
- Push
- Push that resizes
- Average cost per push
This is the stack you usually get from a standard library: a slice with append in Go, a list in Python, an ArrayDeque in Java (the documentation of Java's own Stack class recommends a Deque instead). "Without a limit" means the same thing it means for the linked list: the stack grows until memory runs out. This pop also never shrinks the array, so a stack that once held a million values keeps the room for a million until it's freed.
Try it yourself
Every operation below runs on two stacks at once, one built on an array with room for six values and one built on a linked list. These are the fixed array and the linked list from above. Push past six: the array overflows and stops, while the list allocates one more node. Then pop, and look at the slot just past top in the array: the value is still there, because popping only moves top.
Keyboard and mouse
- Space
- play or pause
- ←→
- previous or next step
- HomeEnd
- start or end of the run
- <>
- slower or faster
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
- every step of the next run shows up here
- every step of the next run shows up here
Common operations and their costs
| Operation | Time | Why |
|---|---|---|
| push | O(1) | Always adds to the top |
| pop | O(1) | Always removes from the top |
| peek | O(1) | Direct read of the top element |
| Search by value | O(n) | Must pop or scan every element |
| Access by position | O(n) | No index, must pop down to that level |
All three core operations are O(1) because each one touches only the top. Anything that needs an element below it costs O(n).
Stacks in the real world
The function call stack. Every time your program calls a function, the runtime pushes a stack frame onto the call stack. That frame holds the function's local variables, its parameters, and the return address, where to continue when the function finishes.
void c() { /* ... */ }void b() { c(); }void a() { b(); }int main() { a(); // call stack at deepest point: // [ main | a | b | c ] ← c is on top}When c returns, its frame is popped and b resumes. When b returns, its frame is popped and a resumes. Function calls nest, so the last one to start is always the first one to finish, which is LIFO.
The call stack follows LIFO, but it isn't a stack in the ADT sense. A stack only lets you touch the top, and code reads and writes below the top of the call stack all the time. A function reaches its own locals and parameters by an offset from the start of its frame, not by popping them. When b passes &x to c, c writes into b's frame, one level below its own. And the stack trace you read after a crash comes from the runtime walking every frame, top to bottom, without popping any. What the call stack keeps from the ADT is the order frames come and go: the last function called is always the first one to return. It's a region of memory managed in LIFO order, and you couldn't swap it for a linked-list stack that only exposes peek.
Undo and redo. Every text editor's undo history is a stack. Each action pushes a state; undo pops the most recent one. A second stack holds undone actions for redo: popping from the undo stack pushes onto the redo stack.
Bracket matching. To verify that brackets are balanced ({[()]} is valid, {[(])} is not), you push every opening bracket and pop when you see a closing one. If the popped bracket matches the closing one, continue. If not, the expression is invalid. If the stack isn't empty at the end, brackets are unclosed.
Depth-first search. Graph traversal using depth-first search (DFS) relies on a stack, either an explicit one or the implicit call stack through recursion. When you reach a node, push its unvisited neighbors, then pop the next node to visit and repeat. Because the most recently found neighbor comes out first, the search follows one path as deep as it goes before backing up.
Browser back button. A browser's back button is a stack of visited URLs. Navigating to a page pushes the current URL. Clicking back pops the most recent URL. The forward button is a second stack, just like undo/redo.
When Stacks fall short
A stack is the wrong choice when a problem needs more than the top.
No random access. You can't reach the 3rd element without popping the 2nd and 1st first. If you need to inspect or modify elements at arbitrary positions, a stack is the wrong structure.
Only one accessible end. Stacks only expose the top. If your problem requires accessing both the front and the back, like a task queue that can be dequeued from either end, use a deque (double-ended queue) instead.
Fixed capacity (array-based). If the maximum depth isn't known ahead of time, an array-based stack needs either a generous overestimate or the growable array described above. The linked-list variant avoids this too, but trades cache efficiency for flexibility.
Poor for search. Finding a specific value requires popping everything above it, which destroys the original stack order. Use a different structure when search is a primary operation.
Summary
- LIFO discipline: the last element in is always the first one out
- O(1) push, pop and peek: all three operations touch only the top; search and access by position cost O(n)
- Three implementation paths: a fixed array (bounded, cache-friendly), a linked list (unbounded, pointer overhead), or an array that doubles when full (unbounded, cache-friendly, amortized O(1) push), which is what most standard libraries use
- The call stack: frames are pushed and popped in LIFO order on every call, including every recursive one, though code reads below its top, so it isn't a stack in the ADT sense