Sikau

Data structures · Day 5 · about 30 min

Stacks

Last in, first out: undo, call stacks and bracket matching.

The plate pile

A stack only lets you add or remove at the top — last in, first out (LIFO). Undo history, the browser's back button and the JavaScript call stack all work this way. An array's push and pop make a perfect O(1) stack.

A Stack class and an undo history

class Stack {
  #items = [];
  push(x) { this.#items.push(x); }
  pop() { return this.#items.pop(); }
  peek() { return this.#items[this.#items.length - 1]; }
  get size() { return this.#items.length; }
  isEmpty() { return this.#items.length === 0; }
}

let text = "";
const undo = new Stack();
function type(s) { undo.push(text); text += s; }
function undoLast() { if (!undo.isEmpty()) text = undo.pop(); }

type("Hello");
type(", world");
type("!!!");
undoLast();
console.log(text, "| undo levels:", undo.size);

The rest of this lesson

  • The call stackexplain
  • Undo and redoexplain
  • What's popped?predict
  • Bracket matchingorder
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 13 lessons of Data structures