Skip to main content
← Advanced CS Study Guide

Code Scholars Tutoring · Advanced CS

4.2 Queue Behavior

How it works

A queue adds at the rear and removes from the front, so items leave in arrival order. That fits scheduling and level-by-level exploration.

Reach for a queue whenever fairness or breadth-first order matters.

Common error

Confusing the two disciplines under pressure; the traversal you get depends entirely on which you chose.

Worked example

Java snippets run inside a main method. Add import java.util.*; when collection types are used.

Java

Queue<String> queue = new ArrayDeque<String>();
queue.offer("A"); queue.offer("B");
System.out.println(queue.poll());
System.out.println(queue.peek());

Output

A
B

A queue removes the earliest waiting item first. This order fits ordinary service lines and breadth-first graph exploration when all traversed edges have equal cost.

A is at the front of the queue and B is at the rear.
The next poll removes A because it entered first.

Exercises

4.2.1 · Explain

Starting empty, enqueue 4, enqueue 9, dequeue, enqueue 2. Give the remaining dequeue order.

Show solution

The first dequeue removes 4. The remaining order is 9, then 2.

4.2.2 · Write code

Use a queue to print 3, 1, 4 in their insertion order.

Show solution

Append at the rear and remove from the front.

One valid solution

Queue<Integer> q = new ArrayDeque<Integer>();
q.offer(3); q.offer(1); q.offer(4);
while (!q.isEmpty()) System.out.print(q.poll() + " ");

Expected output

3 1 4 
Open Java compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic