DSAbeginner 7 min
Last in, first out. Push, pop and peek, and see a stack in action.
What a stack is, its three operations, and where stacks show up in real software.
The undo button, the browser back button and function calls all use stacks. Many tricky interview problems (matching brackets, evaluating expressions) become easy once you reach for a stack.
A stack follows LIFO: Last In, First Out. The newest item is the first one out.
x on top.All three take O(1) time because you only ever touch the top.
In JavaScript, an array already works as a stack: push adds to the end, pop removes from the end.
Press play to watch the stack grow and shrink.
(empty)
An empty stack. Last in, first out.
push calls stack A, B, C, with C on top.peek shows the top, C, without removing it.pop() removes and returns C, the last one in.A, B, and the new top is B.Use a stack to reverse the word "stack": push each letter, then pop them all into a result.
stack.length first.shift and unshift (front of the array) and getting O(n) operations.push, pop, peek are all O(1).Next: queues, the opposite of a stack.
const stack = [];
stack.push("A");
stack.push("B");
stack.push("C");
console.log(stack); // [ 'A', 'B', 'C' ]
console.log(stack.pop()); // C
console.log(stack[stack.length - 1]); // peek: B
console.log(stack); // [ 'A', 'B' ]