---
title: Applications of Stack in Data Structure, With Examples
url: https://www.masaischool.com/resources/applications-of-stack-in-data-structure
description: Applications of a stack in data structures: call stack, undo and redo, bracket matching, postfix, DFS, browser history and monotonic stack, with tested code.
updated: 2026-11-17
publisher: Masai (https://www.masaischool.com)
---

# Applications of Stack in Data Structure: Real-World Uses, Patterns and Code Examples

> **Short answer**
>
> A stack is a last-in, first-out (LIFO) structure, so it is used wherever the most recent item must be handled first. Its main applications are the function call stack, undo and redo, matching brackets, evaluating expressions, depth-first search, browser back and forward history and monotonic-stack problems. Push, pop and peek each take O(1) time.

A stack works like a pile of plates: you add to the top and take from the top, so the last plate you put down is the first one you pick up. That single rule explains every use below.

Each application has a short example that runs as written. They were run on Python 3.9 and Node 24 on 11 November 2026 and the output shown is the real output.

## What a stack is

A stack supports **push** (add to the top), **pop** (remove from the top) and **peek** (read the top without removing it). In Python a plain list is a good stack, because [the documentation](https://docs.python.org/3/tutorial/datastructures.html) shows append() as push and pop() as pop. In JavaScript, arrays give you push() and pop(). In Java, use ArrayDeque: the documentation for the old Stack class says [a Deque should be used in preference](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Stack.html).from collections import deque stack = [] # a plain list is a fine stack: the end is the top stack.append("page 1") # push stack.append("page 2") stack.append("page 3") print(stack[-1]) # peek: look at the top without removing it print(stack.pop(), stack.pop()) # pop: last in, first out print(stack, len(stack) == 0) # is it empty? # deque has the same push and pop at the right end, with O(1) at both ends d = deque(["a", "b"]) d.append("c") print(d.pop(), list(d))

Output:page 3 page 3 page 2 ['page 1'] False c ['a', 'b']

| Operation | Time |
|---|---|
| Push | O(1) |
| Pop | O(1) |
| Peek at the top | O(1) |
| Check whether it is empty | O(1) |
| Search for an item | O(n) |

## Main applications of a stack

| Application | Why a stack fits |
|---|---|
| Function calls (the call stack) | The function called last must finish first, then control returns to its caller |
| Undo and redo | The latest change is the first one undone |
| Bracket and tag matching | The most recent opening bracket must be closed first |
| Evaluating and converting expressions | Operands wait on the stack until their operator arrives |
| Depth-first search and backtracking | The most recent branch point is revisited first |
| Browser back and forward | Back returns to the page you left last |
| Monotonic stack problems | Keeps candidates in sorted order and drops the ones that can no longer win |
| Reversing data | Pushing then popping returns items in reverse order |
| Parsing in compilers and editors | Nested structures close in the reverse order they open |

## Seven applications, each with runnable code

### Application 1: the call stack

When a function calls another, the language pushes a frame onto the **call stack**, and pops it when the function returns. MDN defines the [call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack) as the mechanism an interpreter uses to keep track of what function is running and what it called. This is also why [recursion](https://www.masaischool.com/resources/what-is-recursion) can crash with a stack overflow: too many frames pile up. This code prints each push and pop:def countdown(n, depth=0): pad = " " * depth print(pad + f"push countdown({n})") if n > 0: countdown(n - 1, depth + 1) print(pad + f"pop countdown({n})") countdown(2)

Output:push countdown(2) push countdown(1) push countdown(0) pop countdown(0) pop countdown(1) pop countdown(2)

The last function pushed, countdown(0), is the first popped. Reading a stack trace after an error is reading this stack from the top down.

### Application 2: undo and redo

Use two stacks. Every edit pushes the previous text onto the undo stack. Undo moves the current text onto the redo stack and restores the one on top of undo. A new edit empties the redo stack, because the old future no longer exists.class Editor: def __init__(self): self.text = "" self.undo_stack = [] # earlier versions of the text self.redo_stack = [] # versions we stepped back from def type(self, chunk): self.undo_stack.append(self.text) self.redo_stack.clear() # a new edit ends the redo history self.text += chunk def undo(self): if self.undo_stack: self.redo_stack.append(self.text) self.text = self.undo_stack.pop() def redo(self): if self.redo_stack: self.undo_stack.append(self.text) self.text = self.redo_stack.pop() e = Editor() e.type("Hello") e.type(", world") e.undo() print(repr(e.text)) e.redo() print(repr(e.text)) e.undo() e.type("!") e.redo() # nothing to redo after a new edit print(repr(e.text))

Output:'Hello' 'Hello, world' 'Hello!'

### Application 3: matching brackets

Push every opening bracket. On a closing bracket, the top of the stack must be its partner. At the end the stack must be empty, or some bracket was never closed. Code editors and compilers use this idea to check syntax.def is_balanced(text): pairs = {")": "(", "]": "[", "}": "{"} stack = [] for ch in text: if ch in "([{": stack.append(ch) # remember every opener elif ch in pairs: if not stack or stack.pop() != pairs[ch]: return False # closer with no matching opener return not stack # leftover openers mean unbalanced for s in ["{[()]}", "([)]", "((", "a(b)c[d]"]: print(repr(s), is_balanced(s))

Output:'{[()]}' True '([)]' False '((' False 'a(b)c[d]' True

### Application 4: evaluating postfix expressions

In **postfix** (reverse Polish) notation the operator comes after its operands, as in 2 1 + 3 * for (2 + 1) * 3. No brackets or precedence rules are needed: read left to right, push numbers, and when you meet an operator pop two numbers, apply it and push the result. Converting normal (infix) expressions into postfix is also done with a stack, in the shunting-yard algorithm.def eval_postfix(tokens): """Postfix (reverse Polish) notation: operands first, then the operator.""" stack = [] for t in tokens: if t in "+-*/": b, a = stack.pop(), stack.pop() # the right operand was pushed last if t == "+": stack.append(a + b) elif t == "-": stack.append(a - b) elif t == "*": stack.append(a * b) else: stack.append(int(a / b)) # integer division that rounds toward zero else: stack.append(int(t)) return stack[0] print(eval_postfix("2 1 + 3 *".split())) # (2 + 1) * 3 print(eval_postfix("4 13 5 / +".split())) # 4 + 13 / 5

Output:9 6

### Application 5: depth-first search without recursion

Depth-first search (DFS) always explores the most recently found vertex, which is exactly what a stack gives. A recursive DFS uses the call stack. The version below uses its own stack, and both print the same order. Use this form when a graph is deep enough to hit the recursion limit. See [graph data structure explained](https://www.masaischool.com/resources/graph-data-structure-explained) for the full picture.graph = { "A": ["B", "C"], "B": ["A", "D"], "C": ["A", "D", "E"], "D": ["B", "C", "F"], "E": ["C", "F"], "F": ["D", "E"], } def dfs_recursive(node, seen=None, order=None): seen = set() if seen is None else seen order = [] if order is None else order seen.add(node) order.append(node) for nxt in graph[node]: if nxt not in seen: dfs_recursive(nxt, seen, order) # the call stack remembers where we were return order def dfs_with_stack(start): seen, order, stack = set(), [], [start] # the same idea with our own stack while stack: node = stack.pop() if node in seen: continue seen.add(node) order.append(node) for nxt in reversed(graph[node]): # reversed, so A's first neighbour is popped first if nxt not in seen: stack.append(nxt) return order print(dfs_recursive("A")) print(dfs_with_stack("A"))

Output:['A', 'B', 'D', 'C', 'E', 'F'] ['A', 'B', 'D', 'C', 'E', 'F']

### Application 6: browser back and forward

A browser keeps the pages behind you and ahead of you as two stacks. The back() method of the browser's History object [moves back one page in the session history](https://developer.mozilla.org/en-US/docs/Web/API/History/back), and visiting a new page clears the forward pages. This JavaScript model shows the logic:class BrowserHistory { constructor(home) { this.current = home; this.back = []; // pages behind us (top = the page we left last) this.forward = []; // pages ahead of us, filled when we go back } visit(url) { this.back.push(this.current); this.current = url; this.forward.length = 0; // visiting a new page clears "forward" } goBack() { if (this.back.length) { this.forward.push(this.current); this.current = this.back.pop(); } return this.current; } goForward() { if (this.forward.length) { this.back.push(this.current); this.current = this.forward.pop(); } return this.current; } } const h = new BrowserHistory("home"); h.visit("search"); h.visit("article"); console.log(h.goBack(), h.goBack()); console.log(h.goForward()); h.visit("video"); console.log(h.goForward(), h.current);

Output:search home search video video

After two backs the user is on home. One forward goes to search. Visiting video clears what was ahead, so a forward press changes nothing and the current page stays video.

### Application 7: the monotonic stack

A **monotonic stack** keeps its items in sorted order. Whenever a new item breaks the order, you pop items until the order is restored, and each popped item has just found its answer. The classic use is "for each element, find the next greater one". Each index is pushed once and popped once, so the whole scan is O(n), not O(n^2).// For each day, how many days until a warmer day (0 if there is none)? function daysToWarmer(temps) { const answer = Array(temps.length).fill(0); const stack = []; // indexes of days still waiting for (let i = 0; i < temps.length; i++) { while (stack.length && temps[stack[stack.length - 1]] < temps[i]) { const j = stack.pop(); // day j has found its warmer day answer[j] = i - j; } stack.push(i); } return answer; } console.log(daysToWarmer([30, 32, 31, 35, 28, 29, 33]).join(" "));

Output: 1 2 1 0 1 1 0

Day 0 (30) waits 1 day for 32. Day 1 (32) waits 2 days, until 35. Day 3 (35) never meets a warmer day, so it is 0. The same pattern solves next greater element, stock span and largest rectangle in a histogram.

## Stack vs queue

|  | Stack | Queue |
|---|---|---|
| Order | Last in, first out (LIFO) | First in, first out (FIFO) |
| Main operations | push, pop | enqueue, dequeue |
| Typical uses | Call stack, undo, bracket matching, DFS | Scheduling, BFS, buffering |

A queue is covered in [applications of queue](https://www.masaischool.com/resources/applications-of-queue-in-data-structure). Two stacks can build a queue and two queues can build a stack, which interviewers like to ask.

## Common mistakes

- **Popping from an empty stack.** Python raises an IndexError, and JavaScript's pop() quietly returns a missing value. Check the length first.
- **Forgetting the final check.** In bracket matching, a leftover opener means the text is not balanced.
- **Using list.pop(0) and calling it a stack.** A stack pops from the end. Popping from the front is queue behaviour and costs O(n) on a list.
- **Storing values when you need indexes.** In monotonic stack problems you usually need the position, so push indexes.
- **Unbounded recursion.** Every call adds a frame. Add a base case, or switch to an explicit stack.

## Practice problems, in order

1. [Valid Parentheses](https://leetcode.com/problems/valid-parentheses/)
2. [Min Stack](https://leetcode.com/problems/min-stack/)
3. [Evaluate Reverse Polish Notation](https://leetcode.com/problems/evaluate-reverse-polish-notation/)
4. [Implement Queue using Stacks](https://leetcode.com/problems/implement-queue-using-stacks/)
5. [Daily Temperatures](https://leetcode.com/problems/daily-temperatures/)
6. [Next Greater Element I](https://leetcode.com/problems/next-greater-element-i/)
7. [Decode String](https://leetcode.com/problems/decode-string/)
8. [Simplify Path](https://leetcode.com/problems/simplify-path/)
9. [Basic Calculator II](https://leetcode.com/problems/basic-calculator-ii/)
10. [Largest Rectangle in Histogram](https://leetcode.com/problems/largest-rectangle-in-histogram/)

Masai's longer guide: [Stack in Data Structure: Operations, Code, Applications](https://www.masaischool.com/blog/stack-data-structure-explained-with-examples/). Related pages: [linked lists](https://www.masaischool.com/resources/linked-list-explained), which can back a stack, [hash maps](https://www.masaischool.com/resources/hashmap-explained) and the [DSA learning path](https://www.masaischool.com/resources/data-structures-and-algorithms). To practise with real contests, see [coding practice websites](https://www.masaischool.com/resources/tools/coding-practice-websites).

## Frequently asked questions

### What are the applications of a stack?

The function call stack, undo and redo, matching brackets and tags, evaluating and converting expressions, depth-first search and backtracking, browser back and forward, reversing data and monotonic-stack problems.

### What are real-life examples of a stack?

A pile of plates, a stack of books, the undo button in a text editor and the back button in a browser all work last in, first out.

### Why is a stack used in recursion?

Each recursive call needs its own copy of the local variables and a place to return to. The language stores these in a frame on the call stack. The last call made is the first to finish, which is last-in, first-out.

### Where is a stack used in a compiler?

To check that brackets and blocks match, to parse nested expressions, and to convert expressions between infix and postfix form so they can be evaluated.

### What is the difference between a stack and a queue?

A stack removes the most recent item first (LIFO). A queue removes the oldest item first (FIFO). Stacks suit undo and DFS. Queues suit scheduling and BFS.

### What is a stack overflow?

An error that happens when the call stack runs out of space, usually because a recursive function has no base case or goes too deep. In Python it appears as a RecursionError, and in Java as a StackOverflowError.

### What does LIFO mean in a stack?

Last in, first out: the most recently added item is the first to be removed, like the top plate on a pile.

## Sources checked

- [Using lists as stacks: append() and pop()](https://docs.python.org/3/tutorial/datastructures.html)
- [Deque preferred over the Stack class](https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/Stack.html)
- [Definition of the call stack](https://developer.mozilla.org/en-US/docs/Glossary/Call_stack)
- [History.back() moves back one page in the session history](https://developer.mozilla.org/en-US/docs/Web/API/History/back)
- [Existing Masai post (HTTP 200 on 11 Nov 2026)](https://www.masaischool.com/blog/stack-data-structure-explained-with-examples/)
