A girl and a robot thinking together

Think together · Start with a story

A girl and a robot line up to borrow books. The person who arrives first is helped first; later arrivals join the end of the line.

Break down the process

Follow the numbered steps, then explain them in your own words
  1. Alex arrivesAt the front
  2. The girl arrivesJoins behind
  3. The robot arrivesJoins the back
  4. Service orderAlex, girl, robot

A queue processes items in first-in, first-out order.

Adding at the back and removing from the front preserves the arrival order. Unlike a stack, the last one to arrive does not leave first.

Join at the back, leave from the front

Read from left to right as front to back. Guess which person will leave first.

Step 1 · Person 1 arrives
1

Person 1 is both the front and the back for now.

Step 2 · Person 2 arrives
12

Person 2 joins behind person 1.

Step 3 · Person 3 arrives
123

Person 3 joins at the back, not at the front.

Step 4 · Serve one person
23

Person 1 leaves first, and person 2 becomes the new front.

01What is a queue?

A queue is a data structure that processes items in the order they arrive.

First in, first out (FIFO)

02Why is it like waiting in line to buy a ticket?

In an ordinary line, the person who arrives first is usually served first.

First in, first out (FIFO)

03Where do items enter and leave a queue?

Back

New items join here.

Front

The earliest item is removed from here.

04What are common operations?

push

Add to the back.

pop

Remove from the front.

front

Look at the front item.

back

Look at the back item.

05How do you use a queue in C++?

#include <queue>

std::queue<int> q;
q.push(10);
q.push(20);

std::cout << q.front(); // 10
q.pop();

06What problems can queues solve?

  • Print jobs
  • Message processing
  • Breadth-first search (BFS)
  • Processing requests in arrival order

07Are queues always fair?

An ordinary FIFO queue processes items in arrival order, but real systems may have additional rules such as priority, timeouts, or cancellation.

What you have learned

  • A queue follows first-in, first-out.
  • New items join at the back; older items leave from the front.
  • front looks at the front item, and back looks at the back.
  • Queues are often used to process tasks in arrival order.
  • BFS is an important application of queues.

Next: Linked Lists: Data Can Hold Hands

Your turn to try

If 1, 2, and 3 join a queue in that order, who leaves first?

Ready? Open to see the explanation

1, because it arrived first. After it leaves, 2 becomes the front.