Conceptintro
Stack
Also called stack, LIFO, last in first out, push and pop, std::stack, Stack<T>, ArrayDeque as a stack.
A stack is a collection that gives back its items in reverse order: the last item pushed is the first item popped. Most languages use a growable array or a library type as a stack.
- Applies to
- core-languages
Idea
A stack is a pile of items where only the top item is in reach. Wikipedia defines it as "an abstract data type that serves as a collection of elements with two main operations": push, which adds an item, and pop, "which removes the most recently added element".1 It adds: "The order in which elements are added to or removed from a stack is described as last in, first out, referred to by the acronym LIFO."1
A stack is the right tool when the most recent open item must close first. Brackets in code are an example: each closing bracket must match the last bracket that is still open.
PAIRS = {")": "(", "]": "[", "}": "{"}
def balanced(text: str) -> bool:
stack = []
for ch in text:
if ch in "([{":
stack.append(ch)
elif ch in PAIRS:
if not stack or stack.pop() != PAIRS[ch]:
return False
return not stack
for text in ["f(a[0], {b: 1})", "(]", "((x)", "x)"]:
print(text, "yes" if balanced(text) else "no")
f(a[0], {b: 1}) yes
(] no
((x) no
x) no
How it works
Operations. A stack has three usual operations:
- push adds an item on top;
- pop removes the top item and returns it;
- peek (or top) returns the top item and does not remove it.
Wikipedia says that a peek operation "can, without modifying the stack, return the value of the last element added".1 Most libraries also give the size and a test for an empty stack.
Underflow and overflow. A peek or a pop on an empty stack is an error. Wikipedia: "If the stack is empty, an underflow condition will occur".1 Languages report this in different ways: an exception, a special value such as undefined or None, or undefined behavior. A stack with a fixed capacity can also be full. Wikipedia calls that state "stack overflow".1
Two implementations. A stack is usually an array with a count of items, or a linked list:
- In an array, the top is the last used slot. Wikipedia notes that adding items to or removing items from the end of a dynamic array "requires amortized O(1) time".1 This is the usual choice.
- In a singly linked list, the top is the head of the list. Wikipedia: "A stack may be implemented as, for example, a singly linked list with a pointer to the top element."1 Each push allocates a node.
Where programs use stacks. A stack holds the work that is still open: the open brackets in a parser, the steps to undo in an editor, and the places to go back to in a search. Wikipedia names backtracking as an "important application of stacks", and it calls depth-first search "The prototypical example of a backtracking algorithm".1 The call stack of a running program is also a stack. Each call pushes a frame and each return pops it. See the call stack and recursion. A loop with an explicit stack can do the work of a recursive function without deep calls.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Idiom | |
| C# | Standard library | |
| JavaScript | Idiom | |
| TypeScript | Idiom | TypeScript uses a JavaScript array as a stack, with push, pop and at(-1). The type of pop() includes undefined. No example file exists. |
| Go | Idiom | |
| Rust | Standard library | |
| Kotlin | Standard library | Kotlin has ArrayDeque with addLast and removeLast, and a MutableList works the same way. No example file exists because kotlinc is not installed. |
| SQL | Idiom | A table with an order column can hold a stack. A pop reads and deletes the row with the largest order value. |
| Bash | Idiom | An indexed array works as a stack. A push appends an element, and a pop reads the last element and unsets it. No example file exists. |
| PowerShell | Standard library | [System.Collections.Generic.Stack[T]] gives the .NET stack with Push, Pop and Peek. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML is markup. It has no data structures for a program. |
| CSS | Does not apply | CSS style rules have no data structures. |
| Regular expressions | Does not apply | A regular expression matches text. It has no data structures. |
Few languages have a type that is only a stack. Most programs use a growable array, because pushes and pops at its end are fast.
| Language | Verdict | Form |
|---|---|---|
| Python | idiom | a list, with append and pop()2 |
| JavaScript | idiom | an array, with push and pop |
| TypeScript | idiom | an array, as in JavaScript |
| Java | stdlib | ArrayDeque through the Deque interface; the old Stack class34 |
| C | idiom | an array and a count of items |
| C++ | stdlib | std::stack, an adaptor over std::deque by default5 |
| C# | stdlib | Stack<T>6 |
| Go | idiom | a slice, with append and a slice expression |
| Rust | stdlib | Vec, with push, pop and last7 |
| Kotlin | stdlib | ArrayDeque or a MutableList |
| PowerShell | stdlib | [System.Collections.Generic.Stack[T]] from .NET |
| Bash | idiom | an indexed array |
| SQL | idiom | a table with an order column |
| Regex | n/a | a pattern has no data structures |
| HTML/CSS | n/a | markup and style rules have no data structures |
Python. The tutorial says that "The list methods make it very easy to use a list as a stack, where the last element added is the first element retrieved".2 It continues: "To add an item to the top of the stack, use append() . To retrieve an item from the top of the stack, use pop() without an explicit index."2
Java. The Stack class "represents a last-in-first-out (LIFO) stack of objects" and extends Vector.3 Its documentation says: "A more complete and consistent set of LIFO stack operations is provided by the Deque interface and its implementations, which should be used in preference to this class."3 When a deque is used as a stack, "elements are pushed and popped from the beginning of the deque".4 ArrayDeque "is likely to be faster than Stack when used as a stack".8
C++. "The std::stack class is a container adaptor that gives the programmer the functionality of a stack - specifically, a LIFO (last-in, first-out) data structure."5 It "pushes and pops the element from the back of the underlying container, known as the top of the stack".5 Its pop has the return type void: it removes the top element and returns nothing.9 A program reads top() first and then calls pop().
C#. Stack<T> "Represents a variable size last-in-first-out (LIFO) collection of instances of the same specified type."6 The remarks say: "Stack is implemented as an array."6 TryPop and TryPeek return a value that "indicates whether there is an object at the top of the Stack".6
Rust. The collections guide lists the cases to use a Vec, and one of them is "You want a stack."7 Vec::pop "Removes the last element from a vector and returns it, or None if it is empty."10
JavaScript. "If you call pop() on an empty array, it returns undefined ."11 The program must check for that value.
Go. Go has no stack type. A slice works as one: the built-in append pushes, and a slice expression such as s[:len(s)-1] pops.12 An index outside the slice causes a run-time panic, so s[len(s)-1] on an empty slice panics.12
The example files push three items, peek, pop them in reverse order and show what happens on an empty stack.
stack = []
for item in ["a", "b", "c"]:
stack.append(item)
print(stack, "top", stack[-1])
print(stack.pop(), stack.pop(), stack)
stack.pop()
print("empty:", "yes" if not stack else "no")
try:
stack.pop()
except IndexError as error:
print("IndexError:", error)
['a', 'b', 'c'] top c
c b ['a']
empty: yes
IndexError: pop from empty list
- Verdict: idiom. A
listis the stack.appendpushes,pop()with no index pops, andstack[-1]peeks. - An empty list is false in a condition, so
not stacktests for an empty stack. popon an empty list raisesIndexError.
#include <initializer_list>
#include <iostream>
#include <stack>
#include <string>
int main() {
std::stack<std::string> stack;
for (const char *item : {"a", "b", "c"}) {
stack.push(item);
}
std::cout << "size " << stack.size() << " top " << stack.top() << '\n';
// pop returns void, so read top first.
std::string first = stack.top();
stack.pop();
std::string second = stack.top();
stack.pop();
std::cout << first << ' ' << second << " left " << stack.size() << '\n';
stack.pop();
std::cout << "empty: " << (stack.empty() ? "yes" : "no") << '\n';
}
size 3 top c
c b left 1
empty: yes
- Verdict: stdlib.
std::stackis an adaptor overstd::dequeby default. It givespush,pop,top,sizeandempty, and no iteration. popreturns nothing, so the program readstop()before eachpop().- The program checks
empty()first, becausetoporpopon an empty stack is not allowed.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.NoSuchElementException;
public class Main {
public static void main(String[] args) {
Deque<String> stack = new ArrayDeque<>();
for (String item : new String[] {"a", "b", "c"}) {
stack.push(item);
}
System.out.println(stack + " top " + stack.peek());
System.out.println(stack.pop() + " " + stack.pop() + " " + stack);
stack.pop();
System.out.println("empty: " + (stack.isEmpty() ? "yes" : "no"));
System.out.println("peek on empty: " + stack.peek());
try {
stack.pop();
} catch (NoSuchElementException e) {
System.out.println("pop on empty: NoSuchElementException");
}
}
}
[c, b, a] top c
c b [a]
empty: yes
peek on empty: null
pop on empty: NoSuchElementException
- Verdict: stdlib.
ArrayDequethrough theDequeinterface is the stack.push,popandpeekwork at the front of the deque, so the deque prints the top first. peekon an empty deque returnsnull, andpopthrowsNoSuchElementException.- An
ArrayDequedoes not acceptnullitems.
#include <stdbool.h>
#include <stdio.h>
#define CAPACITY 3
struct stack {
char items[CAPACITY];
int count;
};
static bool push(struct stack *s, char c) {
if (s->count == CAPACITY) {
return false; /* overflow */
}
s->items[s->count++] = c;
return true;
}
static bool pop(struct stack *s, char *out) {
if (s->count == 0) {
return false; /* underflow */
}
*out = s->items[--s->count];
return true;
}
int main(void) {
struct stack s = {.count = 0};
for (const char *p = "abc"; *p != '\0'; p++) {
push(&s, *p);
}
printf("count %d top %c\n", s.count, s.items[s.count - 1]);
printf("push d: %s\n", push(&s, 'd') ? "yes" : "no");
char c = 0;
const char *sep = "";
while (pop(&s, &c)) {
printf("%s%c", sep, c);
sep = " ";
}
printf("\npop on empty: %s\n", pop(&s, &c) ? "yes" : "no");
return 0;
}
count 3 top c
push d: no
c b a
pop on empty: no
- Verdict: idiom. C has no stack type. A fixed array and a count of items make a bounded stack.
pushandpopreturnfalseon overflow and underflow, so the caller must check them.
var stack = new Stack<string>();
foreach (var item in new[] { "a", "b", "c" })
{
stack.Push(item);
}
Console.WriteLine($"{string.Join(",", stack)} top {stack.Peek()}");
Console.WriteLine($"{stack.Pop()} {stack.Pop()} left {stack.Count}");
stack.Pop();
Console.WriteLine($"TryPop on empty: {(stack.TryPop(out var top) ? top : "no")}");
try
{
stack.Pop();
}
catch (InvalidOperationException)
{
Console.WriteLine("Pop on empty: InvalidOperationException");
}
c,b,a top c
c b left 1
TryPop on empty: no
Pop on empty: InvalidOperationException
- Verdict: stdlib.
Stack<T>hasPush,PopandPeek, and it enumerates from the top. Popon an empty stack throwsInvalidOperationException.TryPopreturnsfalseinstead.
const stack = [];
for (const item of ["a", "b", "c"]) {
stack.push(item);
}
console.log(stack.join(","), "top", stack.at(-1));
console.log(stack.pop(), stack.pop(), stack.join(","));
stack.pop();
console.log("empty:", stack.length === 0 ? "yes" : "no");
console.log("pop on empty:", stack.pop());
a,b,c top c
c b a
empty: yes
pop on empty: undefined
- Verdict: idiom. An array is the stack.
pushandpopwork at its end, andat(-1)peeks. popon an empty array returnsundefinedand does not throw.
package main
import "fmt"
func main() {
var stack []string
for _, item := range []string{"a", "b", "c"} {
stack = append(stack, item)
}
fmt.Println(stack, "top", stack[len(stack)-1])
pop := func() (string, bool) {
if len(stack) == 0 {
return "", false
}
top := stack[len(stack)-1]
stack = stack[:len(stack)-1]
return top, true
}
first, _ := pop()
second, _ := pop()
fmt.Println(first, second, stack)
pop()
if _, ok := pop(); !ok {
fmt.Println("pop on empty: no value")
}
// Without the check, the index is out of range and Go panics.
defer func() { fmt.Println("recovered:", recover()) }()
_ = stack[len(stack)-1]
}
[a b c] top c
c b [a]
pop on empty: no value
recovered: runtime error: index out of range [-1]
- Verdict: idiom. A slice is the stack.
appendpushes, andstack[:len(stack)-1]drops the top item. - The
popfunction returns a second value that tells whether the stack had an item. - An index outside the slice panics at run time.
fn main() {
let mut stack: Vec<&str> = Vec::new();
for item in ["a", "b", "c"] {
stack.push(item);
}
let top = stack.last();
println!("{stack:?} top {top:?}");
let first = stack.pop();
let second = stack.pop();
println!("{first:?} {second:?} {stack:?}");
stack.pop();
println!("pop on empty: {:?}", stack.pop());
}
["a", "b", "c"] top Some("c")
Some("c") Some("b") ["a"]
pop on empty: None
- Verdict: stdlib. A
Vecis the stack.pushandpopwork at its end, andlastpeeks. popandlastreturn anOption, so an empty stack givesNoneand not a crash.
Variations and related ideas
- Bounded stack. A stack with a fixed capacity, as in embedded code or in a fixed array in C. A push on a full stack fails.
- Persistent stack. A singly linked list where push makes a new head and keeps the old list. Several versions of the stack share their tails. See linked-list.
- Deque. A double-ended queue can work as a stack and as a queue. Java and Rust use deque types as stacks. See Deque.
- Queue. A queue gives items back in arrival order, first in first out. See Queue.
- Stack machines. Some virtual machines keep the operands of instructions on a stack. Wikipedia: "Many virtual machines are also stack-oriented, including the p-code machine and the Java Virtual Machine."1
Pitfalls
A copy through the constructor reverses a C# stack
A C# Stack<T> enumerates from the top. The constructor that takes a collection pushes the items in that order, so the copy has the old top at the bottom. The .NET example shows this: it creates "a copy of the stack with the order of the elements reversed".6
This code runs but gives a wrong answer on purpose.
var stack = new Stack<string>();
stack.Push("a");
stack.Push("b");
stack.Push("c");
var copy = new Stack<string>(stack);
Console.WriteLine($"{string.Join(",", stack)} | {string.Join(",", copy)}");
Console.WriteLine($"top {stack.Peek()} | top {copy.Peek()}");
c,b,a | a,b,c
top c | top a
To keep the order, copy the array in reverse: new Stack<string>(stack.Reverse()).
Java's Stack and ArrayDeque print in opposite orders
The old Stack class is a Vector, so it keeps the bottom item at index 0.3 An ArrayDeque used as a stack pushes at the front.4 Both pop the same item, but iteration and toString show the items in opposite orders.
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> old = new Stack<>();
Deque<Integer> stack = new ArrayDeque<>();
for (int i = 1; i <= 3; i++) {
old.push(i);
stack.push(i);
}
System.out.println("Stack " + old + " peek " + old.peek());
System.out.println("ArrayDeque " + stack + " peek " + stack.peek());
}
}
Stack [1, 2, 3] peek 3
ArrayDeque [3, 2, 1] peek 3
Code that prints or iterates a stack must not depend on the order when it changes from one type to the other.
Pop on an empty JavaScript array gives undefined
pop on an empty array does not throw. It returns undefined, and the error appears later.11
This code runs but gives a wrong answer on purpose.
const stack = [];
const top = stack.pop();
console.log(top, top + 1);
undefined NaN
Check stack.length before the pop. In the same case, Python raises IndexError, Java's ArrayDeque.pop throws NoSuchElementException, Rust returns None and Go panics.241012
Cost
| Operation | Array stack | Linked-list stack |
|---|---|---|
| push | amortized constant | constant, with one allocation |
| pop | constant | constant |
| peek | constant | constant |
| find an item | linear | linear |
| memory per item | the item, plus spare capacity | the item and one link |
An array stack sometimes grows. The .NET reference says: "If the capacity needs to be increased to accommodate the new element, Push becomes an O(n ) operation".6 The average cost of a push stays constant, because the array doubles in size or grows by a similar factor. An array stack also reads its items from one block of memory, so it is fast in practice.
History
Wikipedia says that "Stacks entered the computer science literature in 1946". In that year, Alan Turing used the terms bury and unbury "as a means of calling and returning from subroutines".1 Konrad Zuse's Z4 already had subroutines and a two-level stack in 1945.1 Klaus Samelson and Friedrich L. Bauer of the Technical University of Munich proposed a stack called Operationskeller ("operational cellar") in 1955 and filed a patent in 1957.1 In March 1988, Bauer received the IEEE Computer Pioneer Award "for the invention of the stack principle".1 Charles Leonard Hamblin developed similar ideas in 1954.1
References
- Stack (abstract data type), Wikipedia, the introduction; History; Non-essential operations; Implementation; Applications of stacks
- The Python Tutorial, 5. Data Structures, 5.1.1 Using Lists as Stacks
- Stack (Java SE 27 and JDK 27), the class description
- Deque (Java SE 27 and JDK 27), the interface description; removeFirst
- std::stack, cppreference.com, the introduction; Template parameters
- Stack<T> Class, .NET API reference, the summary; Examples; Remarks; Methods
- Module std::collections, The Rust Standard Library, When Should You Use Which Collection?
- ArrayDeque (Java SE 27 and JDK 27), the class description
- std::stack::pop, cppreference.com, the description
- Struct Vec, The Rust Standard Library, pop
- Array.prototype.pop(), MDN Web Docs, Return value; Description
- The Go Programming Language Specification, Index expressions; Appending to and copying slices
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 2CAHD7 Edit this page History Report an error Markdown