Data Structures
Stack
push: O(1) · pop: O(1) · peek: O(1). All three are instant because you only ever touch the top item.
The idea, in plain English
A stack is a pile of plates. You add a plate on top. You take the top plate off first. The last thing you add is the first thing you remove. This rule is called LIFO, short for Last In, First Out.
How it works
- 1push: put a new item on top.
- 2pop: remove the top item. This is the most recent one you added.
- 3peek: look at the top item without removing it.
When you'd use it
Use a stack for an app's undo button, a browser's back button, or checking if brackets in code match up.
Common beginner mistakes
- Don't try to grab an item from the middle. A stack only lets you touch the top item.
- Don't pop from an empty stack without checking first. This can cause an error.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Expected output — hit Run to try it
Top: 3
Pop: 3
Pop: 2
Remaining: 1See it in motion
Watch the stackStack · LIFOpush: O(1) · pop: O(1) · peek: O(1). All three are instant because you only ever touch the top item.
top ↓
empty
Ready. Press play — push adds to the top, pop removes from the top.
0
Size
—
Last op
0/5
Step
0/0
Pushes/Pops
Entering / leavingTop of stackIn the stack
Not sure this is the right topic? See the learning paths → or where this leads →