Stacks and Queues Basics
Data structures are the building blocks of efficient algorithms. Among the most fundamental are stacks and queues. Understanding how they work and when to use them is essential for any programmer.
What Is a Stack?
A stack follows the Last‑In‑First‑Out (LIFO) principle. Think of a stack of plates: the last plate placed on top is the first one you take off.
// Simple stack implementation in JavaScript
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
What Is a Queue?
A queue follows the First‑In‑First‑Out (FIFO) principle. Imagine a line at a ticket counter: the first person in line is served first.
// Simple queue implementation in JavaScript
class Queue {
constructor() {
this.items = [];
}
enqueue(element) {
this.items.push(element);
}
dequeue() {
return this.items.shift();
}
front() {
return this.items[0];
}
isEmpty() {
return this.items.length === 0;
}
}
When to Use Each
- Stack: Function call management, undo mechanisms, syntax parsing.
- Queue: Task scheduling, breadth‑first search, buffering data streams.
Leave a Comment