A stack is a linear data structure that adds and removes items at one end only, the top, so the last item in is the first out (LIFO). Push, pop and peek all work at the top, in O(1) time. This page explains how it works, with step-by-step animations of the browser's Back button, a balanced-parentheses check and an array-based stack from the VisiGrab app.
// how stacks work
A stack is a linear data structure that adds and removes items at one end only, the top. It is an abstract data type (ADT), defined by its operations rather than by how they are built. An array or a linked list can sit underneath, and the app builds it both ways.
In LIFO order, the last item added is the first one removed. The name is an analogy to a stack of plates: a plate is added or taken off only at the top. Add 1, 2 and 3, and they come back out as 3, 2 and 1.
Push adds an item on top. Pop removes the top item and returns it. Peek, also called top, returns the top item and leaves it in place. isEmpty tells whether the stack holds no items, and size returns how many it holds. A bounded stack also has isFull. Each takes O(1) time, amortized when a push has to grow a dynamic array. There is no access by index: to reach a lower item, everything above it must be popped. On an empty stack, pop and peek fail: this is underflow.
A web browser can keep the addresses of previously viewed pages on a stack. The current page is not on it: Back needs only the pages before it. In the player, loading pages 2 and 3 pushes addresses 1 and 2, and two Backs pop them, returning to page 1.
A Forward button needs a second stack. Back pushes the current page onto it, and Forward pops a page from it. Visiting a new page clears the Forward stack: its pages no longer follow the current one.
A balance check reads an expression left to right: push each opening parenthesis, pop one at each closing parenthesis, pass over everything else. If the stack is empty at the end, every opening parenthesis has been matched, so the parentheses are balanced. In the player, a checker reads ((5+3)+1)(2+9) one character per step. The stack empties after ((5+3)+1), but the check goes on, and it ends empty: balanced.
The app's second example, (((8+7)-4), ends with one ( left over: unbalanced. The app shows it step by step. A ) that meets an empty stack, as in ())(, makes the expression unbalanced at once. With one bracket type, a counter would do. With (, [ and {, each pop must also check that the brackets match, or ([)] would pass. This is the valid parentheses interview problem: O(n) time, up to O(n) space.
An array-based stack keeps its items in an array, with an index top for the top item; top = -1 means the stack is empty. Push increments top and writes the value there. Pop returns data[top] and decrements top. The top of the stack is always the last used cell, so nothing shifts, and both take O(1). In the player, 5, 0, 7 and 9 are pushed into cells 0 to 3 of a six-cell array, then 9 and 7 are popped, and top falls to 1.
The animation clears a popped cell, but the app's code leaves the value there; the next push overwrites it. A full static array refuses a push. A dynamic array grows instead, typically by doubling and copying the items, so push is O(1) amortized.
Note
A Python list has no fixed size. A bounded stack in Python pre-allocates one, [None] * capacity, and push checks top against the capacity.
A linked-list-based stack keeps each item in a node with a link to the next. The top of the stack is the first node, and the head link that leads to it is called top in the app's code. Push inserts a node at the beginning: node.next = top, then top = node. Pop saves the top node's data and sets top = top.next. Both are O(1), like insertion at the beginning of any linked list. The tail would make a poor top: removing the last node needs the node before it, which takes an O(n) walk from the head. The app shows push and pop at the head step by step.
Note
In C and C++ a link is a pointer; in Java and Python it is a reference. In C++ a popped node must also be freed with delete.
Stack overflow is a push onto a full stack. Only a bounded stack, such as one on a static array, can overflow: it is full once top = capacity - 1. A stack on a dynamic array or a linked list has no fixed capacity; a push fails only if memory runs out. Stack underflow is a pop or peek on an empty stack: top = -1 in an array, top = null in a linked list.
The "stack overflow" error comes from the call stack. Each function call pushes a frame with its local variables and return address, and each return pops it. Recursion that goes too deep, or never stops, fills the call stack. Java then throws StackOverflowError. Python raises RecursionError, by default after about 1,000 nested calls. A C++ program usually crashes.
Last in, first out: pop always removes the item pushed most recently.
A stack removes the newest item first, a queue the oldest: a stack adds and removes at the top, while a queue adds at the rear and removes at the front. Stack vs queue compares where each is used.
| Operation | Static array | Dynamic array | Linked list |
|---|---|---|---|
| Push | O(1); fails when full | O(1) amortized, O(n) worst case | O(1) |
| Pop | O(1) | O(1), amortized if it shrinks | O(1) |
| Peek, isEmpty, size | O(1) | O(1) | O(1) |
| Search | O(n) | O(n) | O(n) |
Search is not a stack operation. Space is O(n) for a linked list or a dynamic array; a static array takes its whole capacity up front, used or not. An array stores the values side by side, which is cache-friendly. A dynamic array also keeps spare slots and sometimes copies everything. A linked list never resizes, but each node needs an extra link and its own allocation, and the nodes are scattered in memory.
A queue adds at one end and removes at the other, so the first item in is the first out: FIFO.
| Property | Stack | Queue |
|---|---|---|
| Order | LIFO: last in, first out | FIFO: first in, first out |
| Add | Push, at the top | Enqueue, at the rear |
| Remove | Pop, from the top | Dequeue, from the front |
| Suits | Nesting, undo, function calls, depth-first search | Arrival order, print jobs, breadth-first search |
Python has no built-in stack type, so a list is used: append() to push, pop() to pop and stack[-1] to peek. pop() on an empty list raises IndexError. collections.deque works the same way, and queue.LifoQueue is a thread-safe stack. In Java, java.util.Stack extends Vector, a synchronized dynamic array. Its documentation recommends a Deque such as ArrayDeque instead. On an empty ArrayDeque, pop() throws NoSuchElementException and peek() returns null. C++'s std::stack is an adaptor over std::deque by default. pop() removes the top item and returns nothing, so read it with top() first. On an empty std::stack, both are undefined behavior.
The full source code is on GitHub, in Python, Java and C++.
Stack interview problems include valid parentheses, min stack and next greater element.
// in the app
In VisiGrab the stack is a 50-slide show, from push and pop to the linked-list-based stack, played one step at a time.
A full stack of six items next to the LIFO definition. Pop items off and push random numbers back on, and a top marker follows the top.
A second check, (((8+7)-4), leaves one ( on the stack and ends with a red cross. Then a linked-list stack pushes 7 and 9 at the head and pops them again. A note explains the head link, which the code calls top.
Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.
Two tabs: Info, with the key characteristics and a note on abstract data types, and Efficiency, with a complexity table for a linked list, a static array and a dynamic array.
Three stacks in each language: on a static array (a bounded array in Python), on a dynamic array and on a linked list. Notes on the time complexity sit between the listings, with links to the full source on GitHub.
Ten questions to check what you have learned before moving on.
// build your own
Download VisiGrab and step through the Back button, both parentheses checks and the array- and linked-list-based stacks yourself.
The stack is one of 30+ topics. See them all