← All Lessons Lesson 2 / 76
Lesson 2

The Stack: A LIFO Data Structure

Meet the Stack

Some problems only make sense when you handle the most recent item first. The last thing you put away is the first thing you take back out. This pattern has a name: LIFO, which stands for *Last In, First Out*. To work this way naturally, we use a data structure called a stack.

A stack is a *linear container* — that just means items sit one after another in a line. But a stack adds one strict rule:

> You can only add an item or remove an item from one end.

That single restriction is what gives the stack its LIFO behavior. Because everything goes in and comes out through the same end, whatever you put in last is always sitting on top, so it must come out first.

A Stack of Plates

The easiest way to picture this is a stack of plates on a kitchen shelf.

  • You put a clean plate on the top of the pile.
  • The next plate goes on top of that one, and so on.
  • When you need a plate, you naturally take the one from the top.

Could you yank a plate out from the bottom? Not without lifting off everything above it first. The plates physically force you to work from the top only.

Imagine adding plates one by one: Plate 1, then Plate 2, Plate 3, Plate 4, Plate 5. Plate 5 is now on top. When you start removing them, the order is Plate 5, then Plate 4, then Plate 3, Plate 2, and finally Plate 1 — the reverse of how they went in. The last plate added is the first one removed. That is LIFO in real life.

From Plates to Data

When we copy this same idea into a programming language to store and retrieve values, we call it the stack data structure. The "plates" become data items — numbers, text, or anything else — and the "top" becomes the single end where all the action happens.

Picture a stack holding the integers 1, 4, 5, 2, 7 (with 1 at the bottom and 7 on top). It behaves exactly like the plates:

  1. Adding (often called *push*): each new value lands on the top. Add 1, then 2, then 3 — now 3 is on top.
  2. Removing (often called *pop*): you can only take the value currently on top. So you remove 3 first, then 2, then 1.

Notice that adding and removing both happen at the same single end. That is the whole trick — by refusing to touch the middle or the bottom, the stack guarantees LIFO order automatically. You never have to manage the order yourself; the structure does it for you.

Why It Matters

The stack is a core data structure in computer programming. It shows up in many places — undoing actions in an editor, the call history of running functions, checking matching brackets, and more — wherever the "handle the newest thing first" pattern appears. Master the simple plate idea, and you already understand the heart of how a stack works.

The Stack: A LIFO Data Structure
Diagram — click to zoom (scroll / drag to pan)