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.ts
function render(values: number[]) {
return values.join(" -> ");
}
const stack: number[] = [];
for (const value of [10, 20, 30]) {
stack.push(value);
}
const popped: number[] = [];
while (stack.length > 0) {
popped.push(stack.pop());
}
console.log(render(popped));
Complexity
- Time: O(1) per push/pop
- Space: O(n)
Implementation notes
- TypeScript declares
stackandpoppedasnumber[], andrender(values: number[])formats numeric arrays. - Push uses
stack.push(value)for10,20, and30, mutating the same array from[]to[10, 20, 30]. The array end is the stack top. - Pop runs inside
while (stack.length > 0), so the replay never observes anundefinedpop, though TypeScript's arraypop()type is still possiblyundefinedin stricter settings. - Popped values are appended with
popped.push(...). The trace showsstack = [10, 20]withpopped = [30], thenstack = []withpopped = [30, 20, 10]. console.log(render(popped))prints30 -> 20 -> 10. Visible allocation is the short input literal, the stack array, the popped array, and the joined output string; mutation is limited topushandpopoperations.
top
The top is the most recently pushed value.
LIFO
A stack removes values in last-in, first-out order.