AlgoTales · Roadmap

Linked-list stack

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

Where you will meet this in real life

A linked-list stack keeps each item in its own small box that points to the box beneath it. You only hold the top box. Pushing puts a new box on top and popping removes it, and the stack can grow as large as memory allows without a preset limit.

Practical use cases

  • Web app: Browser history with no fixed limit. A research tool lets people open page after page while exploring a topic, and nobody knows how many pages they will visit. Each page is a box pointing to the previous page. The tool never has to pick a maximum size or copy a big array when it fills up.
  • Web app: Unlimited undo for a design tool. A web design tool wants unlimited undo during long sessions. Each action is added as a new top box linked to the earlier ones. Growing costs the same tiny amount for the 5th action as for the 5,000th, so the editor never pauses to resize storage.
  • System: Language runtimes and libraries. Some language runtimes and standard libraries implement stacks as chains, so that they can grow one item at a time without reserving a big block. It also means a stack of one item uses almost no memory, which is helpful when thousands of small stacks exist at once.

The story: The Treasure Hunt Chain

Kabir planned a treasure hunt for the whole mohalla. Each clue card had two things written on it: the clue itself, and the address of the next card. Kabir kept only one card in his pocket: the latest one he had written. That was his head.

Adding a new clue was easy. He wrote the clue, put "next card: the one in my pocket" on it, and then moved the new card into his pocket. Nothing else changed. No matter how many clues already existed, adding one took the same few seconds.

Taking one away worked the same way. Pull the card from the pocket, read it, and replace it with the card named in its "next" spot. Kabir never needed to know how long the chain was, and he never ran out of room like the helmet shelf did, as long as he had paper.

That chain is a linked-list stack. The head of the list is the top of the stack. Push is "insert at head", pop is "remove from head". The trick is to use the front, because the front of a linked list is the only place we can reach in one step.

How to spot this problem, and where you need it

You need a stack that may grow to an unknown and possibly large size, and you do not want to decide a maximum in advance or pay for resizing a big block of memory.

Signs you need it

  • The depth of the stack depends on the user or the data, for example endless browsing or very deep nesting, and nobody can promise a limit.
  • Your array-based version sometimes has to be resized or copied, causing small freezes in the app.
  • You have many stacks, most of them small, and reserving a big array for each wastes memory.

Where to use it in a project

  • Unlimited undo or history features in long editing or browsing sessions.
  • Library or framework code that provides a stack for unknown workloads.
  • Systems with many tiny stacks, for example one per user session or per request.

The solution

Make each item a box holding its value and a link to the box below it, and keep one variable called top that points to the first box. To push, create a box that links to the current top and make it the new top. To pop, read the value in the top box and move top to the box it links to. Both steps change just one link.

Payoff: Before: resizing and copying a big array whenever history grew. After: constant tiny work per action and memory used only for items actually stored.

Explain it like I am 8

A treasure hunt where every clue points to the next clue. You only hold the newest clue. To add one, write a new clue that says "next clue: the one I'm holding", and hold the new one. To remove one, put it down and pick up the clue it was pointing to.

How it works, step by step

  1. Make a Node with two fields: the value and a link called next.
  2. Keep one pointer, head, to the top node. An empty stack has head = null.
  3. push(x): create a node, set its next to the current head, then set head to the new node.
  4. pop(): if head is null, report underflow. Otherwise save head.value, move head = head.next and return the saved value.
  5. peek(): return head.value. Keep a counter if you want size() to be quick too.

The code in four languages

PHP

<?php
// Each node holds a value and a link to the node below it.
class Node {
    public function __construct(public mixed $value, public ?Node $next = null) {}
}

class LinkedStack {
    private ?Node $head = null;                      // top of the stack
    private int $size = 0;

    public function push(mixed $x): void {
        $this->head = new Node($x, $this->head);     // new node points at the old head
        $this->size++;
    }

    public function pop(): mixed {
        if ($this->head === null) throw new UnderflowException('Stack is empty');
        $x = $this->head->value;
        $this->head = $this->head->next;             // old head is forgotten
        $this->size--;
        return $x;
    }

    public function peek(): mixed {
        if ($this->head === null) throw new UnderflowException('Stack is empty');
        return $this->head->value;
    }

    public function size(): int { return $this->size; }
}

$s = new LinkedStack();
$s->push('A');
$s->push('B');
$s->push('C');
echo $s->pop() . PHP_EOL;                            // C
echo $s->peek() . ' ' . $s->size() . PHP_EOL;        // B 2

JavaScript

// Each node holds a value and a link to the node below it.
class Node {
  constructor(value, next = null) {
    this.value = value;
    this.next = next;
  }
}

class LinkedStack {
  constructor() {
    this.head = null;                    // top of the stack
    this.length = 0;
  }

  push(x) {
    this.head = new Node(x, this.head);  // new node points at the old head
    this.length++;
  }

  pop() {
    if (this.head === null) throw new Error('Stack is empty');
    const x = this.head.value;
    this.head = this.head.next;          // old head is forgotten
    this.length--;
    return x;
  }

  peek() {
    if (this.head === null) throw new Error('Stack is empty');
    return this.head.value;
  }

  size() { return this.length; }
}

const s = new LinkedStack();
s.push('A');
s.push('B');
s.push('C');
console.log(s.pop());                    // C
console.log(s.peek(), s.size());         // B 2

Java

public class Main {
    // Each node holds a value and a link to the node below it.
    static class Node<T> {
        T value;
        Node<T> next;
        Node(T value, Node<T> next) { this.value = value; this.next = next; }
    }

    static class LinkedStack<T> {
        private Node<T> head = null;                     // top of the stack
        private int size = 0;

        void push(T x) {
            head = new Node<>(x, head);                  // new node points at the old head
            size++;
        }

        T pop() {
            if (head == null) throw new RuntimeException("Stack is empty");
            T x = head.value;
            head = head.next;                            // old head is forgotten
            size--;
            return x;
        }

        T peek() {
            if (head == null) throw new RuntimeException("Stack is empty");
            return head.value;
        }

        int size() { return size; }
    }

    public static void main(String[] args) {
        LinkedStack<String> s = new LinkedStack<>();
        s.push("A");
        s.push("B");
        s.push("C");
        System.out.println(s.pop());                     // C
        System.out.println(s.peek() + " " + s.size());   // B 2
    }
}

Go

package main

import (
	"errors"
	"fmt"
)

// node holds a value and a link to the node below it.
type node struct {
	value string
	next  *node
}

type LinkedStack struct {
	head *node // top of the stack
	size int
}

func (s *LinkedStack) Push(x string) {
	s.head = &node{value: x, next: s.head} // new node points at the old head
	s.size++
}

func (s *LinkedStack) Pop() (string, error) {
	if s.head == nil {
		return "", errors.New("Stack is empty")
	}
	x := s.head.value
	s.head = s.head.next // old head is forgotten
	s.size--
	return x, nil
}

func (s *LinkedStack) Peek() (string, error) {
	if s.head == nil {
		return "", errors.New("Stack is empty")
	}
	return s.head.value, nil
}

func (s *LinkedStack) Size() int { return s.size }

func main() {
	s := &LinkedStack{}
	s.Push("A")
	s.Push("B")
	s.Push("C")
	popped, _ := s.Pop()
	fmt.Println(popped) // C
	top, _ := s.Peek()
	fmt.Println(top, s.Size()) // B 2
}

Time: O(1) per operation · Extra space: O(n). Push and pop only touch the head. Each item costs one node, which carries a little extra for its link.

Watch out for

  • Pushing at the tail of the list. Then pop needs to walk the whole chain to find the second-last node, and it is slow.
  • Moving head before linking: if you set head to the new node first, you lose the old chain. Link the new node to the old head first.
  • Forgetting to handle the empty case (head is null) in pop and peek.

Quick check

  1. In a linked-list stack, which end of the list is the top?
    • The head (first node)
    • The middle
    • The tail (last node)
  2. push(x) creates a node. What must its next point to?
    • null always
    • The old head
    • Itself
  3. What is a real benefit over the array version?
    • It needs less memory per item
    • It lets you read the middle faster
    • It never overflows until memory is gone