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()isO(n). For large queues there are more efficient implementations, but this version is perfect for learning.
Real-world uses
- Stacks: undo/redo, evaluating expressions, navigating history.
- Queues: pending tasks, printing, processing messages in order.
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