DevPath · Learn to code ESPTEN

Data structures

Stacks and queues

Stacks and queues

They are two ways of organizing data according to how they go in and out.

Stack (LIFO)

LIFO = Last In, First Out: the last one in is the first one out, like a stack of plates. Typical operations: push (to stack) and pop (to unstack).

class Stack {
  constructor() {
    this.items = [];
  }
  push(value) {
    this.items.push(value);
  }
  pop() {
    return this.items.pop();
  }
  peek() {
    return this.items[this.items.length - 1];
  }
  get size() {
    return this.items.length;
  }
}

Queue (FIFO)

FIFO = First In, First Out: the first one in is the first one out, like a line at a store. Operations: enqueue and dequeue.

class Queue {
  constructor() {
    this.items = [];
  }
  enqueue(value) {
    this.items.push(value);
  }
  dequeue() {
    return this.items.shift();
  }
  get size() {
    return this.items.length;
  }
}

In practice, using shift() is O(n). For large queues there are more efficient implementations, but this version is perfect for learning.

Real-world uses

Examples

A stack in action

class Stack {
  constructor() { this.items = []; }
  push(value) { this.items.push(value); }
  pop() { return this.items.pop(); }
  peek() { return this.items[this.items.length - 1]; }
  get size() { return this.items.length; }
}

const history = new Stack();
history.push("page1");
history.push("page2");
console.log("Items:", history.size);   // 2
console.log("Back to:", history.pop());     // page2
console.log("Back to:", history.pop());     // page1
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
← Map and SetLinked lists and trees →