
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
- Alex arrivesAt the front
- The girl arrivesJoins behind
- The robot arrivesJoins the back
- 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.
Person 1 is both the front and the back for now.
Person 2 joins behind person 1.
Person 3 joins at the back, not at the front.
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.
02Why is it like waiting in line to buy a ticket?
In an ordinary line, the person who arrives first is usually served first.
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.
frontlooks at the front item, andbacklooks 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.