Skip to content

Module 1: Stacks (The Pringles Can)

๐Ÿ“š Module 1: Stacks

Course ID: DSA-105
Subject: The Pringles Can

A Stack is a data structure where you can only add or remove items from the Top. It follows the LIFO rule: Last-In, First-Out.


๐Ÿ—๏ธ Step 1: LIFO Logic

๐Ÿงฉ The Analogy: The Pringles Can

  • You put the first chip in the bottom of the can.
  • You put the last chip at the very top.
  • If you want to eat a chip, you MUST eat the Top one first.
  • To get to the bottom chip, you have to remove every other chip above it!

๐Ÿ—๏ธ Step 2: The Two Operations

  1. PUSH: Putting a new item on the top of the stack.
  2. POP: Taking the top item off the stack.
  • Bonus: PEEK: Looking at the top item without removing it.

๐Ÿ—๏ธ Step 3: Why do we use it?

  1. Undo Button: Every time you type, your actions are โ€œPushedโ€ onto a stack. When you hit Ctrl+Z, the last action is โ€œPopped.โ€
  2. The Call Stack: This is how your computer remembers where it is. If Function A calls Function B, the computer โ€œPushesโ€ A onto a stack. When B is finished, it โ€œPopsโ€ A to remember where to return.

๐Ÿฅ… Module 1 Review

  1. LIFO: Last-In, First-Out.
  2. Push/Pop: The only way to interact with the data.
  3. Restricted: You canโ€™t see or touch anything in the middle of the stack.

:::tip Slow Learner Note A stack is just a regular list where we choose to only use one end! You can implement a stack in Python using a list with just .append() and .pop(). :::