Tutelage

Lessons › coding and computer science · taught by Leo

Stacks and queues basics: LIFO vs FIFO

Learn how stacks and queues store data, and how push/pop and enqueue/dequeue work in LIFO and FIFO order.

Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.app

Two ways to line up data

Think of these as two different rules for handling items.

A stack uses the top item first. A queue uses the oldest item first.

Stack means last in, first out

A stack is like a pile of plates. You add to the top, and you remove from the top.

The rule is last in, first out, or LIFO.

That means the most recent item is the next one out.

Predict the stack rule

If you push A, then B, then C onto a stack, which item comes off first?

  1. A
  2. B
  3. C
Show answer

C: Yes. The top item comes off first.

Push and pop a stack

Watch the stack grow one item at a time.

After three pushes, C is on top.

A pop takes that top item off.

Now B becomes the new top.

Quick check on pop

What does pop do in a stack?

  1. Remove the top item
  2. Remove the oldest item
  3. Add an item to the bottom
Show answer

Remove the top item: Correct. Pop removes the top item.

Queue means first in, first out

A queue is like a line at lunch. You add to the back, and you remove from the front.

The rule is first in, first out, or FIFO.

That means the oldest item leaves first.

Enqueue and dequeue

A queue keeps order by arrival time.

The front item is the next one out.

Dequeue removes from the front.

Then the next person moves up.

Predict the queue rule

If 1, then 2, then 3 enter a queue, which leaves first?

  1. 1
  2. 2
  3. 3
Show answer

1: Yes. The first item in leaves first.

Stack versus queue

Stacks and queues are both ordered lists.

The difference is where you add and remove.

Common mix-up to avoid

A common mistake is mixing up top and front.

For a stack, think top of the pile. For a queue, think front of the line.

Your turn: choose the structure

A printer saves jobs in the order they arrive. Which structure fits best?

  1. Stack
  2. Queue
  3. Neither
Show answer

Queue: Correct. Jobs should print in arrival order, so a queue fits.

Recap: top or front?

Check the first rule: stack or queue?

Then remember the removal side: top or front.

Use LIFO for stacks and FIFO for queues.

Learn this with Leo, freeA voiced lesson with a live whiteboard, quizzes and a tutor you can call, at tutelage.app