The Stack

Improve your mental model of the stack data structure

A typical analogy for the stack data structure is a stack of plates - a collection of items placed on top of one another. The stack has two methods to add and remove items from it’s collection - push and pop.

It is a data structure that works on the principle of last in, first out - meaning that the last item added to the stack is the first one to be removed. The last one in is also the only one that can be read, sometimes via a getter method named peek.

Use cases

The stack data structure is a great use case for managing function call stacks, browser history stacks and requirements that involve undo functionality.

The stack visualised

An interactive example of the stack data structure.

  • 0
  • 1
  • 2
  • 3
3
Peek
4
Length
false
Is empty?

Implementation

Here is an implementation of the stack data structure in TypeScript, using an array to store it’s collection of items. I have included some non-essential methods such as peek, which observes the last element in the stack.

class Stack<T> {
  items: Array<T>;
 
  constructor() {
    this.items = [];
  }
 
  push(item: T): number {
    return this.items.push(item);
  }
 
  pop(): T | undefined {
    return this.items.pop();
  }
 
  isEmpty(): boolean {
    return this.length() === 0;
  }
 
  peek(): T | undefined {
    return this.isEmpty() ? undefined : this.items[this.length() - 1];
  }
 
  length(): number {
    return this.items.length;
  }
}
 
const stack = new Stack();
 
stack.push(1);
stack.push(2);
stack.push(3);
 
console.log(stack.peek()); // 3
console.log(stack.pop()); // 3
console.log(stack.peek()); // 2
console.log(stack.isEmpty()); // false