DEV Community

Sreekar Reddy
Sreekar Reddy

Posted on • Originally published at sreekarreddy.com

πŸ₯ž Stacks Explained Like You're 5

A pile of pancakes, last in first out

Day 38 of 149

πŸ‘‰ Full deep-dive with code examples


The Pancake Stack

Mom makes pancakes and stacks them:

πŸ₯ž ← Last one made (on top)
πŸ₯ž
πŸ₯ž
πŸ₯ž ← First one made (on bottom)
Enter fullscreen mode Exit fullscreen mode

Which pancake do you take first? The top one!

Last In, First Out = LIFO


Stack Operations

Two main things you can do:

  • Push: Add to top
  • Pop: Remove from top
Push "A" β†’ [A]
Push "B" β†’ [A, B]
Push "C" β†’ [A, B, C]
Pop      β†’ [A, B] (returns C)
Pop      β†’ [A] (returns B)
Enter fullscreen mode Exit fullscreen mode

Real Uses

Undo/Redo: Each action is pushed. Undo pops the last one!

Browser Back Button: Each page is pushed. Back pops!

Function Calls:

main() calls
  login() calls
    validate()
Enter fullscreen mode Exit fullscreen mode

When validate() finishes, pop back to login()!


In One Sentence

Stacks store data like a pile where you typically add/remove from the top (last in, first out).


πŸ”— Enjoying these? Follow for daily ELI5 explanations!

Making complex tech concepts simple, one day at a time.

Top comments (0)