Algorithms

Stack (data structure): last in, first out

Cover of the article Stack (data structure): last in, first out
Focused reading

Understand the context.
Put it into practice.

Leia este artigo em português

In this article
  1. How does a stack work?
  2. What is the difference between a stack and a queue?
  3. Stack in Java, Python, PHP and C
  4. Now you ask: do I have to build the stack by hand?
  5. Where do stacks show up day to day?
  6. How do you check parentheses with a stack?
  7. What happens when the stack overflows?
  8. Now it’s your turn!

A stack is a data structure in which the last element that goes in is the first one that comes out. This behavior has a name: LIFO, short for Last In, First Out.

In the article about the linked list, you saw nodes that point to each other, like the clues in a treasure hunt. Today we’ll use that same chain to build a structure your computer uses all the time, without you noticing.

How does a stack work?

Think of a stack of plates. You wash a plate and put it on top of the others. You wash another one and put it on top again. When it’s time to set the table, you take the plate on top, which was the last one washed. Taking the one at the bottom? Only if you take the whole stack apart haha

Three-panel comic with a stack of plates on a counter: the washed plate goes on top of the stack, when setting the table the person takes the plate on top, and the bottom plate, which went in first, is left for last
The stack of plates: in from the top, out from the top.

Notice that everything happens in one single place: the top. A stack has two main operations:

  • Push: puts an element on the top.
  • Pop: removes the element that is on the top.

And two helpers: peek (also called top), which shows who is on the top without removing anyone, and is empty, which tells you whether anyone is left. In books, you’ll also find the name pushdown stack: each new element pushes the others down, just like a plate!

Here is the step by step:

StepOperationStack (from top to bottom)Who left
1Push AnaAnaNobody
2Push BrunoBruno, AnaNobody
3Push CarlaCarla, Bruno, AnaNobody
4PopBruno, AnaCarla
5PopAnaBruno
Step by step of a stack: the last to arrive is the first to leave.
Watch the stack animation, step by step
Animation of a stack in which Ana, Bruno and Carla go in at the top, one on top of the other, and then Carla and Bruno leave from the top, in the reverse order of arrival
The same step by step in motion: three pushes and two pops, always at the top.

What is the difference between a stack and a queue?

A queue does the opposite. In it, whoever arrives first leaves first, like the line at a bakery (FIFO, short for First In, First Out). In a stack, the last to arrive is the one who leaves. Same order of arrival, opposite exits. The queue has an article of its own, with the two side by side.

Stack in Java, Python, PHP and C

Let’s use what you learned in the previous article: our stack will be a linked list in which everything happens at the beginning. The beginning of the list is the top of the stack. To push, the new node points to the old top and becomes the top. To pop, the top becomes the node below it. Here it is in Java:

public class Main {
    static class Node {
        String value;
        Node next;

        Node(String value, Node next) {
            this.value = value;
            this.next = next;
        }
    }

    static class Stack {
        private Node top = null;

        void push(String value) {
            top = new Node(value, top); // the new node points to the old top and becomes the top
        }

        String pop() {
            if (top == null) {
                return null; // empty stack: nothing to remove
            }
            String value = top.value;
            top = top.next; // the one below becomes the top
            return value;
        }

        String peek() {
            return top == null ? null : top.value; // just looks, doesn't remove
        }

        boolean isEmpty() {
            return top == null;
        }
    }

    public static void main(String[] args) {
        Stack stack = new Stack();
        stack.push("Ana");
        stack.push("Bruno");
        stack.push("Carla");

        System.out.println(stack.peek());    // Carla
        System.out.println(stack.pop());     // Carla
        System.out.println(stack.pop());     // Bruno
        System.out.println(stack.isEmpty()); // false
    }
}

In Python:

class Node:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next


class Stack:
    def __init__(self):
        self.top = None

    def push(self, value):
        self.top = Node(value, self.top)  # the new node points to the old top and becomes the top

    def pop(self):
        if self.top is None:
            return None  # empty stack: nothing to remove

        value = self.top.value
        self.top = self.top.next  # the one below becomes the top
        return value

    def peek(self):
        return None if self.top is None else self.top.value  # just looks, doesn't remove

    def is_empty(self):
        return self.top is None


stack = Stack()
stack.push("Ana")
stack.push("Bruno")
stack.push("Carla")

print(stack.peek())  # Carla
print(stack.pop())  # Carla
print(stack.pop())  # Bruno
print(stack.is_empty())  # False

In PHP:

<?php

class Node
{
    public function __construct(
        public string $value,
        public ?Node $next = null,
    ) {
    }
}

class Stack
{
    private ?Node $top = null;

    public function push(string $value): void
    {
        $this->top = new Node($value, $this->top); // the new node points to the old top and becomes the top
    }

    public function pop(): ?string
    {
        if ($this->top === null) {
            return null; // empty stack: nothing to remove
        }

        $value = $this->top->value;
        $this->top = $this->top->next; // the one below becomes the top

        return $value;
    }

    public function peek(): ?string
    {
        return $this->top === null ? null : $this->top->value; // just looks, doesn't remove
    }

    public function isEmpty(): bool
    {
        return $this->top === null;
    }
}

$stack = new Stack();
$stack->push('Ana');
$stack->push('Bruno');
$stack->push('Carla');

echo $stack->peek(), PHP_EOL; // Carla
echo $stack->pop(), PHP_EOL; // Carla
echo $stack->pop(), PHP_EOL; // Bruno
var_dump($stack->isEmpty()); // bool(false)

And in C:

#include <stdio.h>
#include <stdlib.h>

struct Node {
    int value;
    struct Node *next;
};

struct Stack {
    struct Node *top;
};

void push(struct Stack *stack, int value) {
    struct Node *node = malloc(sizeof(struct Node));

    if (node == NULL) {
        return; // out of memory: the stack stays as it was
    }

    node->value = value;
    node->next = stack->top; // the new node points to the old top
    stack->top = node;       // and becomes the top
}

int pop(struct Stack *stack) {
    if (stack->top == NULL) {
        return -1; // empty stack: nothing to remove
    }

    struct Node *old = stack->top;
    int value = old->value;

    stack->top = old->next; // the one below becomes the top
    free(old);
    return value;
}

int peek(const struct Stack *stack) {
    return stack->top == NULL ? -1 : stack->top->value; // just looks, doesn't remove
}

int main(void) {
    struct Stack stack = {NULL};

    push(&stack, 1); // plate 1
    push(&stack, 2); // plate 2
    push(&stack, 3); // plate 3

    printf("%d\n", peek(&stack)); // 3
    printf("%d\n", pop(&stack));  // 3
    printf("%d\n", pop(&stack));  // 2
    printf("%d\n", pop(&stack));  // 1
    printf("%d\n", pop(&stack));  // -1: the stack is empty
    return 0;
}

Notice that push and pop don’t walk through the stack: they only touch the top. With 3 or 3 million elements, the work is the same. In Big O notation, that is written O(1), constant cost. Got it?

In the C example, I used numbers instead of names (plates 1, 2 and 3), and -1 means the stack is empty. Since each node was created with malloc, each pop gives its memory back with free. I ran the program through Valgrind, and not a single byte was left behind.

Now you ask: do I have to build the stack by hand?

To learn, yes! Day to day, you use the stack the language already provides. In Java, the documentation of the Stack class itself says that, for stacks, you should prefer the Deque interface, with the ArrayDeque class:

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    public static void main(String[] args) {
        Deque<String> stack = new ArrayDeque<>();
        stack.push("Ana");
        stack.push("Bruno");
        stack.push("Carla");

        System.out.println(stack.peek()); // Carla
        System.out.println(stack.pop());  // Carla
    }
}

In Python, the list already works as a stack: append pushes and pop without an index pops. The top is the last element, which you peek at with stack[-1]:

stack = []
stack.append("Ana")
stack.append("Bruno")
stack.append("Carla")

print(stack[-1])  # Carla: peeks at the top without removing it
print(stack.pop())  # Carla

PHP has the SplStack class, which uses a doubly linked list under the hood:

<?php

$stack = new SplStack();
$stack->push('Ana');
$stack->push('Bruno');
$stack->push('Carla');

echo $stack->top(), PHP_EOL; // Carla
echo $stack->pop(), PHP_EOL; // Carla

C has no ready-made stack. There, besides the linked list you just saw, it’s very common to keep the stack in an array, with an index that marks the first free position, t. Pushing means storing at position t and adding 1. Popping means subtracting 1 and reading. When t is 0, the stack is empty:

Diagram with the same stack stored in two ways: on top, the top points to the Carla node, which points to Bruno, which points to Ana, the bottom; below, an array with Ana at position 0, Bruno at 1 and Carla at 2, the top, and the index t equal to 3, the first free position
The same stack stored in two ways: with linked nodes or with an array and the index t.

IMPORTANT: in the ready-made stacks, popping an empty stack doesn’t return “nothing”: the program stops with an error. I tested it here. Python shows IndexError: pop from empty list. Java shows java.util.NoSuchElementException. And PHP shows RuntimeException with the message Can't pop from an empty datastructure. So, before popping, check whether the stack is empty!

Where do stacks show up day to day?

  • Undo (Ctrl+Z): every action you take goes onto a stack. Undo removes the last one, which is the first to be undone.
  • The browser’s back button: the pages you visit pile up, and back takes you to the most recent one first.
  • Call stack: remember the recursion article? Each function call goes onto a stack and leaves it when it finishes.
  • Checking parentheses: to know whether every opened parenthesis was closed in the right order, the program uses a stack. It’s a classic application, and you’ll see the code right below.

How do you check parentheses with a stack?

That last example is a classic and worth a closer look. The rule is: parentheses, brackets and braces must be closed in the reverse order in which they were opened. Reverse order is exactly how a stack works! Every time something opens, push. Every time something closes, pop and check whether it’s the right pair. At the end, the stack must be empty:

Symbol readWhat the stack doesStack (bottom to top)
(Push(
[Push( [
]Pops the [: it’s the right pair(
)Pops the (: it’s the right pairempty
Checking ([]): at the end the stack is empty, so the symbols are balanced.

Now the same reasoning in code, in the four languages (click the tabs):

import java.util.ArrayDeque;
import java.util.Deque;

public class Main {
    static char pair(char closing) {
        return closing == ')' ? '(' : closing == ']' ? '[' : '{';
    }

    static boolean isBalanced(String text) {
        Deque<Character> stack = new ArrayDeque<>();

        for (char symbol : text.toCharArray()) {
            if (symbol == '(' || symbol == '[' || symbol == '{') {
                stack.push(symbol); // opened: push it
            } else if (symbol == ')' || symbol == ']' || symbol == '}') {
                if (stack.isEmpty() || stack.pop() != pair(symbol)) {
                    return false; // closed without opening, or closed the wrong type
                }
            }
        }

        return stack.isEmpty(); // anything left open? then it isn't balanced
    }

    public static void main(String[] args) {
        String[] texts = {"(a + b) * [c - d]", "(a + b]", "((a + b)"};

        for (String text : texts) {
            System.out.println(text + " -> " + isBalanced(text));
        }
    }
}
def is_balanced(text):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []

    for symbol in text:
        if symbol in "([{":
            stack.append(symbol)  # opened: push it
        elif symbol in pairs:
            if not stack or stack.pop() != pairs[symbol]:
                return False  # closed without opening, or closed the wrong type

    return not stack  # anything left open? then it isn't balanced


for text in ["(a + b) * [c - d]", "(a + b]", "((a + b)"]:
    print(text, "->", is_balanced(text))
<?php

function isBalanced(string $text): bool
{
    $pairs = [')' => '(', ']' => '[', '}' => '{'];
    $stack = new SplStack();

    foreach (str_split($text) as $symbol) {
        if (str_contains('([{', $symbol)) {
            $stack->push($symbol); // opened: push it
        } elseif (isset($pairs[$symbol])) {
            if ($stack->isEmpty() || $stack->pop() !== $pairs[$symbol]) {
                return false; // closed without opening, or closed the wrong type
            }
        }
    }

    return $stack->isEmpty(); // anything left open? then it isn't balanced
}

foreach (['(a + b) * [c - d]', '(a + b]', '((a + b)'] as $text) {
    echo $text, ' -> ', isBalanced($text) ? 'true' : 'false', PHP_EOL;
}
#include <stdio.h>

#define N 100

int is_balanced(const char *text) {
    char stack[N];
    int t = 0; // t marks the first free position: with 0, the stack is empty

    for (int i = 0; text[i] != '\0'; i++) {
        char symbol = text[i];

        if (symbol == '(' || symbol == '[' || symbol == '{') {
            if (t == N) {
                return 0; // full stack: nothing else fits
            }
            stack[t++] = symbol; // opened: push it
        } else if (symbol == ')' || symbol == ']' || symbol == '}') {
            char expected = symbol == ')' ? '(' : symbol == ']' ? '[' : '{';

            if (t == 0 || stack[--t] != expected) {
                return 0; // closed without opening, or closed the wrong type
            }
        }
    }

    return t == 0; // anything left open? then it isn't balanced
}

int main(void) {
    const char *texts[] = {"(a + b) * [c - d]", "(a + b]", "((a + b)"};

    for (int i = 0; i < 3; i++) {
        printf("%s -> %d\n", texts[i], is_balanced(texts[i]));
    }
    return 0;
}

Output in Java:

(a + b) * [c - d] -> true
(a + b] -> false
((a + b) -> false

All four reach the same result. Only the way of writing true and false changes: Python shows True and False, and C shows 1 and 0. The first text is correct. In the second, the ( was closed with ]. In the third, a ( was left open. Focus on the concept, not the language!

What happens when the stack overflows?

The call stack has a limited size. If a function calls itself nonstop, like the example without a base case in the recursion article, the calls pile up until no more fit. See it in Java:

public class Main {
    static void forever(int n) {
        forever(n + 1); // I left out the base case on purpose
    }

    public static void main(String[] args) {
        forever(1);
    }
}

The first lines of the output:

Exception in thread "main" java.lang.StackOverflowError
	at Main.forever(Main.java:3)
	at Main.forever(Main.java:3)
	at Main.forever(Main.java:3)

The line at Main.forever repeats more than a thousand times: these are the calls left piled up, waiting for an answer that never came. This is the famous stack overflow. The Java documentation describes StackOverflowError exactly like that: the error thrown when an application recurses too deeply.

Now it’s your turn!

Use your stack to reverse a word: “stack” has to become “kcats”. Before typing, think: in what order do the letters come out of the stack?

Try it on your own, without asking anyone for the ready-made answer, not even AI! You are fully capable of solving it. Then compare it with mine:

See the answer
def reverse(word):
    stack = Stack()

    for letter in word:
        stack.push(letter)  # the first letter goes to the bottom

    reversed_word = ""
    while not stack.is_empty():
        reversed_word += stack.pop()  # the last letter comes out first

    return reversed_word


print(reverse("stack"))  # kcats
print(reverse("stressed"))  # desserts

The function uses the Stack class you created above. Push all the letters and then pop them all: the first letter goes to the bottom and comes out last. As a bonus, “stressed” becomes “desserts” haha

In the next article, you’ll meet the queue, which does exactly the opposite: whoever arrives first is the first to leave. See you there!

Stay confident!!!

Sources:

  • Princeton University, Robert Sedgewick and Kevin Wayne. Algorithms, 4th edition: 1.3 Bags, Queues, and Stacks, with the pushdown stack, a collection based on the last-in-first-out (LIFO) policy.
  • Princeton University, COS 226. Bags, Queues, and Stacks lecture, with the client that reverses a sequence of strings with a stack and the stack implemented with an array or with a linked list.
  • Princeton University, Introduction to Programming in Java. Stack.java, with push, pop, peek and isEmpty implemented with a singly linked list.
  • Oregon State University, CS 261. Chapter 6: Stacks, with the browser’s Back button, which works because the browser keeps a stack of the pages visited.
  • Kansas State University, CC 310. Stacks Summary, with the text editor’s undo and the browser’s back as applications of stacks.
  • Runestone Academy, Problem Solving with Algorithms and Data Structures using Java. Basic Balanced Parentheses, with the stack popped to match each closing symbol.
  • National and Kapodistrian University of Athens. Stacks, with the rule that the parentheses are balanced if the stack is empty at the end and every matched pair is of the same type.
  • Kansas State University, CIS 300. Week 3 lecture notes, with the Java Virtual Machine using a stack to remember the methods that were called but are not finished yet.
  • Python documentation. Data Structures (using lists as stacks), with append, which adds to the top, and pop without an index, which removes from the top.
  • Oracle, Java 21 documentation. Class Stack, with the recommendation to use the Deque interface and its implementations instead of the Stack class.
  • PHP Manual. The SplStack class, with a stack implemented on top of a doubly linked list in LIFO mode.
  • Java SE 21 documentation. Class StackOverflowError (copy hosted by EPFL), with the error thrown when an application recurses too deeply.
  • Boise State University. Computer Science Two: Example: Stack, with the undo of text editors implemented with a stack of actions.
  • The examples were run on Java 21, Python 3.13, PHP 8.3 and GCC 13. The C program also went through Valgrind, with no memory leaks.

Share this article

About the author

Walmir Silva

Hi! I'm Walmir, a software engineer with an MBA in Software Engineering, the mind behind GrowthCode and the author of the book "Além do Código" (in Portuguese).

If you think programming is just about writing code, get ready to broaden your horizons. Here, we go beyond the code and explore the fascinating intersections between technology, business, the arts and philosophy.

Are you looking for career growth? Do you want to stand out in a competitive market? Are you after a life richer in knowledge and fulfillment? Then you've come to the right place. At GrowthCode, we offer deep insights, proven strategies and a touch of philosophical wisdom to fuel your personal and professional growth.

See all articles →

Continue the conversation

Share your perspective

Your email address will not be published. Required fields are marked *

We keep the IP address and browser of commenters for 6 months, to block spam and because Brazil’s Marco Civil da Internet requires access records to be kept for that period. See how we handle your data (in Portuguese).

Find your next answer

What do you want to learn?

Cookie preferences

Optional cookies start off. You can change your choice at any time on this screen.

NecessaryAlways on

They store your cookie choice and its record code, and keep the site working. They are not used for advertising.

They count visits and show how the site is used: Google Analytics and Microsoft Clarity, loaded by Google Tag Manager.

They show Google AdSense ads without personalization. The cookies in this category limit how often ads repeat and measure their results.

Uses your browsing to choose ads and build ad audiences: Google ads chosen by your interests and Google signals in Analytics. When off, ads are shown without personalization. Requires Advertising.

You can also block cookies in your browser settings. Details in the Privacy policy (in Portuguese).