AlgoTales · Roadmap

Stack implementation

Beginner · 8 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

A stack is a pile where you can only add to the top and take from the top, so the last thing put in is the first thing out. It is simple, but many everyday features, like Undo and the Back button, are really stacks in disguise.

Practical use cases

  • Web app: Undo in a text or form editor. In an online document editor, every edit is pushed onto a pile of actions. Pressing Ctrl+Z pops the latest one and reverses it, and pressing it again reverses the one before. The editor never has to search for what to undo, because the newest action is always sitting on top.
  • Web app: The Back button in a single-page app. A React app remembers the screens a user visited: product list, product page, cart. Each navigation pushes a screen, and Back pops one and shows the previous. Users move back through exactly the path they took, in reverse order, which is what they expect.
  • System: The call stack and calculators. When one function calls another, the computer pushes a note about where to return to, and pops it when the function finishes. Compilers and calculators also use stacks to hold unfinished work while they read an expression. This is why the error "stack overflow" exists: the pile grew too tall.

The story: The Tiffin Tower Rules

Every morning Mira's mother packed a steel tiffin tower: dal at the bottom, rice above it, roti on top. At school Mira loved opening it, but there was one strict rule of the tower: you can only reach the top box. To get the dal, you must lift off everything above it.

Her brother Kabir, who was learning to code, said, "Mira, your lunch box is a data structure!" He drew four little buttons on a sheet. push puts a box on top. pop takes the top box off and gives it to you. peek lets you look at the top without touching. isEmpty asks whether the tower has any box left at all.

"But why make a rule that I can touch only the top?" Mira asked. Kabir grinned. "Because rules make things fast and safe. Adding and removing at the top never disturbs the boxes below, so each button takes the same tiny effort, whether the tower holds three boxes or three thousand."

That is a stack: Last In, First Out. The last box you put on is the first one you take off. Building one in code means picking a place to keep the boxes and writing exactly those four buttons. The next two lessons show two popular ways to keep them.

How to spot this problem, and where you need it

You must handle things in reverse order of arrival, where the most recent item is the one needed next, and you want adding and removing to be instant and simple.

Signs you need it

  • The feature says undo, back, go to previous, or "last in, first out", and the newest thing must be handled first.
  • You are tracking something that is opened and later closed in nested order, like tags, brackets or function calls.
  • Your code keeps an array and always uses only its last element, calling array_pop and array_push.

Where to use it in a project

  • Undo and redo for editors, drawing tools, form builders and spreadsheets.
  • Navigation history and modal or wizard step tracking in single-page apps.
  • Parsers and checkers that handle nested structures such as HTML, JSON or formulas.

The solution

Keep a list and only touch one end, the top. Push means put a new item on the top. Pop means remove and return the top item. Peek means look at the top without removing it. Also check for empty before popping. Because you never touch the middle, each operation costs the same tiny amount of work however many items are stored.

Payoff: Before: searching a history list to find the last action. After: one pop that returns the latest action immediately.

Explain it like I am 8

A stack is a tower of lunch boxes. You can only put a box on the top or take the top one off. The box you put on last comes off first. You are never allowed to pull one out of the middle!

How it works, step by step

  1. Choose the container that holds the items, like an array or a chain of nodes. The top of the stack is just one end of it.
  2. push(x): add x at the top end.
  3. pop(): if the stack is empty, report an error (underflow). Otherwise remove the top item and return it.
  4. peek(): if not empty, return the top item but leave it in place.
  5. isEmpty() / size(): answer questions about the pile without changing it. Every operation touches only the top, so each is quick.

The code in four languages

PHP

<?php
// A tiny Stack class: the four buttons from the story.
class Stack {
    private array $items = [];

    public function push(mixed $x): void { $this->items[] = $x; }        // add on top

    public function pop(): mixed {
        if ($this->isEmpty()) throw new UnderflowException('Stack is empty');
        return array_pop($this->items);                                  // remove from top
    }

    public function peek(): mixed {
        if ($this->isEmpty()) throw new UnderflowException('Stack is empty');
        return $this->items[count($this->items) - 1];                    // look, do not touch
    }

    public function isEmpty(): bool { return count($this->items) === 0; }
    public function size(): int { return count($this->items); }
}

$tower = new Stack();
$tower->push('Dal');
$tower->push('Rice');
$tower->push('Roti');
echo $tower->pop() . PHP_EOL;          // Roti  (last in, first out)
echo $tower->peek() . PHP_EOL;         // Rice
echo $tower->size() . PHP_EOL;         // 2

JavaScript

// A tiny Stack class: the four buttons from the story.
class Stack {
  constructor() { this.items = []; }

  push(x) { this.items.push(x); }                    // add on top

  pop() {
    if (this.isEmpty()) throw new Error('Stack is empty');
    return this.items.pop();                         // remove from top
  }

  peek() {
    if (this.isEmpty()) throw new Error('Stack is empty');
    return this.items[this.items.length - 1];        // look, do not touch
  }

  isEmpty() { return this.items.length === 0; }
  size() { return this.items.length; }
}

const tower = new Stack();
tower.push('Dal');
tower.push('Rice');
tower.push('Roti');
console.log(tower.pop());     // Roti  (last in, first out)
console.log(tower.peek());    // Rice
console.log(tower.size());    // 2

Java

import java.util.*;

public class Main {
    // A tiny Stack class: the four buttons from the story.
    static class Stack<T> {
        private final List<T> items = new ArrayList<>();

        void push(T x) { items.add(x); }                          // add on top

        T pop() {
            if (isEmpty()) throw new RuntimeException("Stack is empty");
            return items.remove(items.size() - 1);                // remove from top
        }

        T peek() {
            if (isEmpty()) throw new RuntimeException("Stack is empty");
            return items.get(items.size() - 1);                   // look, do not touch
        }

        boolean isEmpty() { return items.isEmpty(); }
        int size() { return items.size(); }
    }

    public static void main(String[] args) {
        Stack<String> tower = new Stack<>();
        tower.push("Dal");
        tower.push("Rice");
        tower.push("Roti");
        System.out.println(tower.pop());     // Roti  (last in, first out)
        System.out.println(tower.peek());    // Rice
        System.out.println(tower.size());    // 2
    }
}

Go

package main

import (
	"errors"
	"fmt"
)

// Stack is a tiny stack: the four buttons from the story.
type Stack[T any] struct {
	items []T
}

func (s *Stack[T]) Push(x T) { s.items = append(s.items, x) } // add on top

func (s *Stack[T]) Pop() (T, error) {
	var zero T
	if s.IsEmpty() {
		return zero, errors.New("Stack is empty")
	}
	x := s.items[len(s.items)-1]
	s.items = s.items[:len(s.items)-1] // remove from top
	return x, nil
}

func (s *Stack[T]) Peek() (T, error) {
	var zero T
	if s.IsEmpty() {
		return zero, errors.New("Stack is empty")
	}
	return s.items[len(s.items)-1], nil // look, do not touch
}

func (s *Stack[T]) IsEmpty() bool { return len(s.items) == 0 }
func (s *Stack[T]) Size() int     { return len(s.items) }

func main() {
	tower := &Stack[string]{}
	tower.Push("Dal")
	tower.Push("Rice")
	tower.Push("Roti")
	top, _ := tower.Pop()
	fmt.Println(top) // Roti  (last in, first out)
	next, _ := tower.Peek()
	fmt.Println(next)         // Rice
	fmt.Println(tower.Size()) // 2
}

Time: O(1) per operation · Extra space: O(n). push, pop, peek and isEmpty only touch the top, so they take the same tiny effort however tall the stack is. Storing n items takes room for n items.

Watch out for

  • Popping or peeking an empty stack without checking first. Always decide what underflow should do (throw an error or return a special value).
  • Treating a stack like a list and reaching into the middle. If you need that, a stack is the wrong tool.
  • Mixing up the top: if the top is the front of an array, every push and pop shifts all items and is no longer quick.

Quick check

  1. You push A, then B, then C. What does pop() return?
    • C
    • A
    • B
  2. What does peek() do?
    • Removes the top item
    • Shows the top item without removing it
    • Shows the bottom item
  3. What is "underflow"?
    • Peeking at a stack with one item
    • Pushing onto a full stack
    • Popping from an empty stack