Stack, step by step.

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 a stack works

What is a stack in data structures?

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.

LIFO: last in, first out

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.

Stack operations: push, pop and peek

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 vertical stack, a container open at the top, holding six items: 7, 4, 2, 0, 1 and 5 from bottom to top. A top marker points to 5. A push arrow leads down into the opening, and a pop arrow leads up out of it.
Push and pop both work at the top: 5, the last item pushed, is the first to be popped.

Stack example: the browser's Back button

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.

The browser's Back button

All steps as text
  1. A stack can be used in a web browser to store and retrieve previously viewed pages.
  2. In this case, the stack contains the web addresses of the visited pages.
  3. When the first web page is loaded (address 1 is its web address), the stack is empty.
  4. When the second web page is loaded, the address of the first page is pushed onto the stack.
  5. Similarly, when the third web page is loaded, the address of the second page is pushed onto the stack.
  6. When we click the "Back" button, the top address is popped from the stack and the browser loads that page.
  7. Page 1 is shown again and the stack is empty: the last address pushed was the first one popped.
Stack — The browser's Back button. Last step: Page 1 is shown again and the stack is empty: the last address pushed was the first one popped.

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.

Balanced parentheses with a stack

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.

Balanced parentheses

All steps as text
  1. A stack can be used to check the balance of parentheses in mathematical expressions.
  2. Push an opening parenthesis onto the stack when encountered, and pop it when a closing parenthesis appears.
  3. If the stack is empty after all parentheses are processed, then the parentheses are balanced.
  4. Each closing parenthesis has popped an opening one, and the stack is empty: the parentheses in ((5+3)+1)(2+9) are balanced.
Stack — Balanced parentheses. Last step: Each closing parenthesis has popped an opening one, and the stack is empty: the parentheses in ((5+3)+1)(2+9) are 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.

Array-based stack

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.

Array-based stack

All steps as text
  1. The stack can be implemented in several ways. One of them is using an array.
  2. Adding (inserting at the end) a value to an array is equivalent to pushing an element onto a stack. That is, the element at the top of the stack is always the last element in the array.
  3. Removing the last element from the array makes the next element down, which has a lower index, the new top of the stack.
  4. 5 and 0 are left, and 0, in the last filled cell, is the top. Push and pop work only at the end of the array, so nothing shifts and both take O(1).
Array-based stack. Last step: 5 and 0 are left, and 0, in the last filled cell, is the top. Push and pop work only at the end of the array, so nothing shifts and both take O(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.

Linked-list-based stack

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.

Four nodes in a row, 9, 7, 0 and 5, each a box with its value and a next cell, linked from each node to the one on its right; 5, the last node, links to nothing. A top label links to 9, the first node, where push and pop work.
In a linked-list-based stack the top is the first node, so push and pop both work at the beginning of the list.

Stack overflow and underflow

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.

What does LIFO mean?

Last in, first out: pop always removes the item pushed most recently.

What is the difference between a stack and a queue?

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.

Stack time complexity: array vs linked list

OperationStatic arrayDynamic arrayLinked list
PushO(1); fails when fullO(1) amortized, O(n) worst caseO(1)
PopO(1)O(1), amortized if it shrinksO(1)
Peek, isEmpty, sizeO(1)O(1)O(1)
SearchO(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.

Stack vs queue

A queue adds at one end and removes at the other, so the first item in is the first out: FIFO.

PropertyStackQueue
OrderLIFO: last in, first outFIFO: first in, first out
AddPush, at the topEnqueue, at the rear
RemovePop, from the topDequeue, from the front
SuitsNesting, undo, function calls, depth-first searchArrival order, print jobs, breadth-first search

Stacks in Python, Java and C++

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++.

Where stacks are used: applications of a stack

  • Undo and redo, with two stacks: undo pops the last action onto a redo stack, and a new action clears it.
  • Function calls and recursion, on the call stack.
  • Expression evaluation: postfix notation (reverse Polish notation) pushes operands, and each operator pops two and pushes the result. Converting infix to postfix uses a stack of operators.
  • Depth-first search of a graph, and backtracking, with an explicit stack in place of recursion.
  • Reversing a string: push every character, then pop them all.
  • Bracket matching in compilers and editors, and the browser's Back button.

Stack interview problems include valid parentheses, min stack and next greater element.

Three animations here.
The whole topic 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.

Push / pop demo

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.

An unbalanced check, a linked list

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.

Forward and back

Step through every slide and step back, or jump to any slide from the list. The show reopens where you left it.

Theory and complexity

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.

Python, Java and C++

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.

Quiz

Ten questions to check what you have learned before moving on.

Build a stack
push by push.

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