What are Stacks useful for?

Nicolai Safai
Code Zest
Published in
3 min readMay 3, 2019

--

When I learned about Stacks, I wondered what a practical use case for them would be. One of the most common use cases for a Stack is to implement “Undo” (e.g. +Z or Ctrl+Z).

To understand why, let’s briefly dive into what a Stack is:

What is a Stack?

A stack is a list of items that can only be changed from one side, called the top of the stack.

Plate dispenser (Image Source)

Plate dispensers are a great real-world analogy to stacks. Plates can only be added or removed from the top of the stack. The last plate you add is the always the first plate you take out. This is referred to as the Last-In-First-Out principle (LIFO).

In more correct terms, stacks allow you to push (=add) items, or pop (=remove) items from the top of the Stack.

Image from Joe Birch

Why use a stack for Undo? We always want to undo the last action.

Stacks only allow us to push() items to the top of the stack, and pop() the item that was just added.

“But what happens if you never Undo? The stack must become huge!”

--

--

Software Engineer | PM | Interested in Music, Design, Psychology & Education. “Make it Happen Captain”