Stacks and Queues
Stack Push/Pop
Push values onto a stack and pop them back in last-in, first-out order.
Algorithm
Basic Implementation
basic.js
function render(values) {
return values.join(" -> ");
}
const stack = [];
for (const value of [10, 20, 30]) {
stack.push(value);
}
const popped = [];
while (stack.length > 0) {
popped.push(stack.pop());
}
console.log(render(popped));
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- JavaScript represents the stack with a mutable
ArrayofNumbervalues.stack.push(value)appends10,20, and30at the end, making the array end the top of the stack. - Pop uses
stack.pop(), which removes and returns the last element in O(1) amortized time for a normal JavaScript array. The samestackarray is mutated in place rather than replaced. - Popped values are collected in a second
Arraywithpopped.push(...). The replay showsstackmoving from[]to[10, 20, 30], then to[10, 20]after popping30, and finally to[]withpopped = [30, 20, 10]. render(popped)usesvalues.join(" -> "), soconsole.logprints the deterministic output30 -> 20 -> 10. Allocation is limited to the short input literal, the stack array, the popped array, and the joined output string, all managed by the JavaScript runtime GC.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.