Data structure · Linear structures

Stack

Last in, first out: push and pop at one end in amortized O(1). The model behind call stacks, undo histories and bracket matching.

The derivations, edge cases and exercises are in the lesson The call stack and the heap. Open it full width in the playground.

On this page
  1. The idea
  2. Operations
  3. Invariants
  4. When to use it
  5. Built-in equivalents
  6. Step through it
  7. Implementation
  8. Learn more
  9. References

The idea

A stack exposes one end only. Push puts an element on top, pop removes the top, peek reads it. Whatever went in last comes out first.

The usual implementation is the end of a dynamic array, so push and pop never shift anything; a linked list with insertions at the head works too.

Representation. The end of a dynamic array (top = last used slot).

Operations

Stack operations and their complexity
OperationTimeExtra spaceNotes
PushO(1) amortizedO(1) amortizedInherits the dynamic array’s occasional resize.
PopO(1)O(1)Fails (underflow) on an empty stack.
PeekO(1)O(1)
SearchO(n)O(1)Not part of the abstract interface.

Invariants

What stays true before and after every operation.

  • Only the top element is accessible.
  • Pop returns elements in exactly the reverse order of their pushes.
  • Popping an empty stack is an error, never a silent default.

When to use it

Use it when

  • The most recent unfinished item must be handled first: nested brackets, expression parsing, undo, depth-first search.
  • You replace recursion with an explicit stack to avoid running out of call stack.

Avoid it when

  • Items must be processed in arrival order (use a queue).
  • You need the minimum or maximum rather than the newest (use a heap).

Built-in equivalents

What the standard library of each language offers. Linked types have a full page in the collections encyclopedia with every operation’s complexity, memory effects and a tested example.

C#

List<T>

Stack<T> wraps an array; List<T> with Add and RemoveAt(Count − 1) works as well.

Python

list

list.append and list.pop() are the idiomatic stack.

Java

ArrayList<E>

ArrayDeque (push, pop, peek) is preferred over the legacy java.util.Stack.

C++

std::vector<T>

std::stack adapts std::deque by default; std::vector with push_back and pop_back is common.

Step through it

The interactive lab for stack: custom and seeded inputs, stepping forward and backward, with the active line highlighted in the code.

Implementation in four languages

The array-backed stack in four languages, checked against one shared fixture of push, pop and peek sequences, including underflow on an empty stack.

namespace Bekadan.Dsa.Examples.StacksQueues;
 
/// <summary>A LIFO stack on the end of a dynamic array: push and pop are amortized O(1).</summary>
public sealed class ArrayStack<T>
{
    private readonly List<T> _items = [];
 
    public int Count => _items.Count;
 
    public IReadOnlyList<T> BottomToTop => _items;
 
    public void Push(T item)
    {
        _items.Add(item); // the end of the array is the top
    }
 
    public T Pop()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The stack is empty.");
        T top = _items[^1];
        _items.RemoveAt(_items.Count - 1); // removing the last element shifts nothing
        return top;
    }
 
    public T Peek()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("The stack is empty.");
        return _items[^1];
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/StacksQueues/ArrayStack.cs

"""An array-backed LIFO stack."""
 
from typing import Generic, TypeVar
 
T = TypeVar("T")
 
 
class ArrayStack(Generic[T]):
    """LIFO on the end of a list: push and pop are amortized O(1)."""
 
    def __init__(self) -> None:
        self._items: list[T] = []
 
    def __len__(self) -> int:
        return len(self._items)
 
    def bottom_to_top(self) -> list[T]:
        return list(self._items)
 
    def push(self, item: T) -> None:
        self._items.append(item)  # the end of the list is the top
 
    def pop(self) -> T:
        if not self._items:
            raise IndexError("pop from an empty stack")
        return self._items.pop()  # removing the last element shifts nothing
 
    def peek(self) -> T:
        if not self._items:
            raise IndexError("peek at an empty stack")
        return self._items[-1]

Tested on CPython 3.14.0 · examples/python/dsa_examples/array_stack.py

package dev.bekadan.dsa.stacks;
 
import java.util.ArrayList;
import java.util.List;
import java.util.NoSuchElementException;
 
/** A LIFO stack on the end of an ArrayList: push and pop are amortized O(1). */
public final class ArrayStack<T> {
    private final List<T> items = new ArrayList<>();
 
    public int size() {
        return items.size();
    }
 
    public List<T> bottomToTop() {
        return List.copyOf(items);
    }
 
    public void push(T item) {
        items.add(item); // the end of the list is the top
    }
 
    public T pop() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The stack is empty.");
        }
        return items.remove(items.size() - 1); // removing the last element shifts nothing
    }
 
    public T peek() {
        if (items.isEmpty()) {
            throw new NoSuchElementException("The stack is empty.");
        }
        return items.get(items.size() - 1);
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/stacks/ArrayStack.java

#pragma once
 
#include <stdexcept>
#include <utility>
#include <vector>
 
namespace bekadan::dsa {
 
// A LIFO stack on the end of a std::vector: push and pop are amortized O(1).
// (std::stack is the standard adapter for this; this class shows the mechanism.)
template <typename T>
class ArrayStack {
public:
    [[nodiscard]] std::size_t size() const noexcept { return items_.size(); }
    [[nodiscard]] const std::vector<T>& bottom_to_top() const noexcept { return items_; }
 
    void push(T item) {
        items_.push_back(std::move(item));  // the end of the vector is the top
    }
 
    T pop() {
        if (items_.empty())
            throw std::underflow_error("pop from an empty stack");
        T top = std::move(items_.back());
        items_.pop_back();  // removing the last element shifts nothing
        return top;
    }
 
    [[nodiscard]] const T& peek() const {
        if (items_.empty())
            throw std::underflow_error("peek at an empty stack");
        return items_.back();
    }
 
private:
    std::vector<T> items_;
};
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/array_stack.hpp

Learn more

Problems, patterns and exercises

References