Stacks appear in function calls, undo and redo histories, and expression evaluation. The useful rule is LIFO, or Last In, First Out: the most recently added item is removed first.
LIFO in practice
A stack adds and removes items at the same end. Here, a JavaScript array holds the items, and its last element is the top of the stack.
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items.pop();
}
peek() {
if (this.isEmpty()) {
return "Stack is empty";
}
return this.items[this.items.length - 1];
}
isEmpty() {
return this.items.length === 0;
}
}
For matching brackets, the last opening bracket must match the next closing bracket:
function isValidParentheses(s) {
const stack = [];
const pairs = { "(": ")", "[": "]", "{": "}" };
for (let char of s) {
if (pairs[char]) {
stack.push(char); // Opening bracket
} else {
if (stack.length === 0) return false;
const last = stack.pop();
if (pairs[last] !== char) return false;
}
}
return stack.length === 0;
}
To reverse an order, I push each item and pop them later:
function reverseString(str) {
const stack = [];
for (let char of str) {
stack.push(char);
}
let reversed = "";
while (stack.length > 0) {
reversed += stack.pop();
}
return reversed;
}
For undo behavior, I store previous states in a stack:
class Editor {
constructor() {
this.content = "";
this.undoStack = [];
}
type(text) {
this.undoStack.push(this.content); // Save state
this.content += text;
}
undo() {
if (this.undoStack.length > 0) {
this.content = this.undoStack.pop();
}
}
}
Complexity and fit
For a stack backed by a dynamic array, push is amortized O(1) and pop is O(1). Storing n items takes O(n) space.
I use a stack when the most recent unfinished item is the one to handle next. In the bracket example, that item is the last opening bracket that has not been closed.

Loading comments...