Visualize Push, Pop, and Peek operations in a Stack. Learn Last-In-First-Out (LIFO) principles with interactive animations.
About this algorithm
A stack is a collection where the last item you put in is the first one you take out, like a pile of plates. You can only touch the top: push adds a new item there, pop removes the item there, and peek reads it without removing it. All three take the same small amount of time however tall the stack is.
Use a stack whenever the newest thing should be dealt with first: undo in an editor, the back button in a browser, the call stack that remembers where each function should return to, and depth-first search, which keeps exploring the path it most recently opened. Pick a queue instead when the oldest item should go first, as in a print queue or breadth-first search. The balanced parentheses and monotonic stack pages show two classic problems where a stack is the whole trick.
Place the new value on top. In an array-backed stack that means appending at the end; in a linked list it means adding a new head node.
First check that the stack is not empty. If it is, there is nothing to remove, and this page returns null. Otherwise take the top value off and return it; the item below becomes the new top.
Check for empty in the same way, then return the top value without removing it. Use it to decide what to do before you commit to a pop.
Clear empties the stack in one go. Keeping a count (or using the array length) answers "how many items" and "is it empty" without looking through the items.
The page opens with three plates: 10 at the bottom, then 20, with 30 on top. Type 40 and push: 40 sits above 30 and is the new top, so the stack holds four values. Peek now returns 40 and changes nothing. Pop returns 40 and 30 is on top again. Pop three more times and you get 30, 20 and 10, the reverse of the order they went in. One more pop finds the stack empty and returns null instead of a value. Notice that 10, the first value pushed, was the last one out.
Popping an empty stack is called underflow, and real code must check for it, as this page does. A stack with a fixed capacity can also overflow when you push onto a full one; this page grows as needed, like a JavaScript array or a Python list.
Time: push, pop and peek each touch only the top item, so they never depend on how many items are below it. Space: the stack stores each of its N items once.