What is a stack?
A stack is a pile you only touch from the top. You push a value on,
pop the newest one off, and never dig underneath — last in, first out
(LIFO). Think of a stack of plates: the one you just set down is the
first one you pick up again.
- Top
- The only end you read or change
- Push
- Place a new value on the top
- Pop
- Remove and return the top value
- LIFO
- Last in, first out — newest leaves first
See it as a pile
Picture a stack of books on a desk. A new book goes on top. When you need one, you take the top book — not the one buried at the bottom.
Watch the pile grow upward on each push, then shrink from the top on each pop. The bottom stays put until everything above it is gone.
Push grows the pile up. Pop always removes the uppermost book.
Types of stacks
Under the hood, stacks usually differ in how they store values and whether they cap how tall they can grow.
Array-backed stacks use a contiguous buffer and a top index. Linked-list-backed stacks hang nodes from the head. Bounded stacks refuse a push past a max size; unbounded ones grow until memory runs out.
Backing answers “how is it stored?” Capacity answers “can it overflow?”
How it is stored in memory
Your language already uses a stack for function calls. Each call pushes a frame; each return pops one. The same LIFO rule runs your program and your data structure.
Press Next to watch frames climb the call stack, then peel off on the way back.
Start here. Each step highlights the TypeScript below.
Operations
Think of the stack as a row that only changes at the end — the rightmost cell is the top. Tap Next on each demo to watch LIFO happen. For class wrappers and interview patterns, open the Functions tab.
Push
Add a value on top. Everything underneath stays exactly where it was.
Top is 9 at the end. Push goes on top — nowhere else.
Pop
Remove the top value and return it. The next value down becomes the new top.
Only the top leaves. You cannot pull 7 from the bottom.
Peek
Look at the top without taking it off. Useful when you need to decide before you pop.
Read the top without removing it. The stack stays the same.
isEmpty
Ask whether anything is left. Empty stacks have no top to peek or pop.
One value left — the stack is not empty.
Search / contains
Walk from the top toward the bottom until you find the value — or run out of plates.
Looking for 7. Start at the top (9) and walk down.
Clear
Wipe the whole pile in one go. After clear, the next push starts a fresh stack.
Clear drops every value at once — top and bottom alike.