A girl and a robot thinking together

Think together · Start with a story

A girl stacks a red plate, then a blue one, then a yellow one. When she needs a plate, she takes one from the top.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Add red plateAt the bottom
  2. Add blue plateOn top of red
  3. Add yellow plateAt the top
  4. Removal orderYellow, blue, red

A stack follows the last-in, first-out rule.

Push adds an element to the top; pop removes the top element. Function calls and matching parentheses are examples of problems that can use this order.

The last item added is the first one removed

Read from left to right as bottom to top. The rightmost item is the one you can remove.

Step 1 · Add the red plate
Red plate

The red plate is now at the top of the stack.

Step 2 · Add the blue plate
Red plateBlue plate

The blue plate becomes the new top.

Step 3 · Add the yellow plate
Red plateBlue plateYellow plate

The yellow plate was added last, so it comes off first.

Step 4 · Remove one item
Red plateBlue plate

The yellow plate is gone. Now the blue plate is at the top.

01What is a stack?

A stack is a data structure where adding and removing items happen at one end, called the top.

Last in, first out (LIFO)

02Why is it like a pile of plates?

You add a plate to the top and take a plate from the top. The last plate you added is the first one you take away.

Last in, first out (LIFO)

03What are push, pop, and top?

push

Put a new element on top of the stack.

pop

Remove the top element.

top

Look at the current top element.

04How does a stack change?

Empty stack→ push AA→ push BB / A→ popA

Each item enters and leaves from the top.

05What problems can stacks solve?

  • Function call stacks
  • Undo operations
  • Matching parentheses
  • Processing expressions
  • Some implementations of DFS

06How do you use a stack in C++?

#include <stack>

std::stack<int> s;
s.push(10);
s.push(20);

std::cout << s.top(); // 20
s.pop();

pop() removes an element but does not return the removed value. If you need to use it, call top() first, then pop().

07Does a stack have to use contiguous memory?

No.

std::stack is a container adapter. By default, it usually uses std::deque as its underlying container, though other suitable containers can be used.

What you have learned

  • A stack follows last-in, first-out.
  • Its main operations happen at the top.
  • push adds an item, pop removes one, and top looks at the top item.
  • A stack is useful when the most recently added item should be handled first.
  • The logical stack model is not the same as a specific memory layout.

Next: Queues: Like Waiting in Line to Buy a Ticket

Your turn to try

If you add 1 and then 2, which one do you remove first?

Ready? Open to see the explanation

2. It was added last, so it is at the top. After removing it, 1 becomes the top item.