Skip to lesson
MentorNxt home

Java Programming

Queues, Stacks & Priority Queues

Common mistakes and practice

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Queues, stacks, deques and priority queues all hold values waiting to be handled. The only real question is which value comes out next, and each structure gives a different answer.

Which one comes out next?

Ask what the next value should be, and the structure follows. All four are usually built on ArrayDeque or PriorityQueue, and all of their main operations are O(1) or O(log n).

Example 1 · Same values, three different orders

WhichNextDemo.javaJava
import java.util.ArrayDeque;import java.util.Deque;import java.util.PriorityQueue;import java.util.Queue;
public class WhichNextDemo {    public static void main(String[] args) {        int[] arrivals = { 30, 10, 50, 20, 40 };
        Queue<Integer> queue = new ArrayDeque<>();        Deque<Integer> stack = new ArrayDeque<>();        Queue<Integer> heap = new PriorityQueue<>();        for (int x : arrivals) {            queue.offer(x);            stack.push(x);            heap.offer(x);        }
        StringBuilder q = new StringBuilder("Queue (oldest first):  ");        StringBuilder s = new StringBuilder("Stack (newest first):  ");        StringBuilder h = new StringBuilder("Heap (smallest first): ");        while (!queue.isEmpty()) {            q.append(queue.poll()).append(" ");            s.append(stack.pop()).append(" ");            h.append(heap.poll()).append(" ");        }        System.out.println(q.toString().trim());        System.out.println(s.toString().trim());        System.out.println(h.toString().trim());    }}
Output
Queue (oldest first):  30 10 50 20 40
Stack (newest first):  40 20 50 10 30
Heap (smallest first): 10 20 30 40 50

What this code does

  • The same five values go into all three structures. Only the rule for "next" differs: arrival order, reverse arrival order, or value order.
  • One while loop can empty all three, because each structure holds exactly five values.
  • The oldest (fair, arrival order) → a queue: Queue<T> q = new ArrayDeque<>() with offer/poll.
  • The newest (undo, back, brackets) → a stack: Deque<T> s = new ArrayDeque<>() with push/pop.
  • Either end (palindromes, bounded history, sliding windows) → a Deque with First/Last methods.
  • The most important (triage, top k, schedulers) → a PriorityQueue with the right comparator.

Mistakes that compile but fail

None of these is caught by the compiler. Each one shows up as a crash or as a wrong order at run time.

Example 2 · Mistake: unboxing an empty poll

UnboxingTrapDemo.javaJava
import java.util.ArrayDeque;import java.util.List;import java.util.Queue;
public class UnboxingTrapDemo {    public static void main(String[] args) {        Queue<Integer> tokens = new ArrayDeque<>(List.of(101, 102));        int served = 0;        for (int i = 0; i < 3; i++) {            int token = tokens.poll();            served++;            System.out.println("Serving token " + token + " (" + served + " served)");        }    }}
Sample output
Serving token 101 (1 served)
Serving token 102 (2 served)
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the return value of "java.util.Queue.poll()" is null
	at UnboxingTrapDemo.main(UnboxingTrapDemo.java:10)

What this code does

  • poll safely returns null on the third pass, but storing it in an int makes Java call intValue() on null. The message says exactly that.
  • Fix: loop with while (!tokens.isEmpty()), or store the result in an Integer and check it for null first.
  • remove(), pop() or element() on an empty structure → NoSuchElementException. Check isEmpty() or use poll/peek.
  • int x = queue.poll(); on an empty queue → null cannot become an int: NullPointerException.
  • Mixing push and offer on one deque, or using the old Stack class, gives surprising orders.
  • Expecting a PriorityQueue to print or loop in sorted order, or changing a priority after offer.

Breadth-first search: a queue explores level by level

Breadth-first search (BFS) explores a network in rings, using a queue: everything one step away first, then two steps away, and so on. The examples below find degrees of connection and a shortest path in a grid.

Example 3 · BFS: degrees of connection

ConnectionsDemo.javaJava
import java.util.ArrayDeque;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Queue;
public class ConnectionsDemo {    public static void main(String[] args) {        Map<String, List<String>> friends = new HashMap<>();        friends.put("Asha", List.of("Bala", "Chitra"));        friends.put("Bala", List.of("Asha", "Dev"));        friends.put("Chitra", List.of("Asha", "Dev", "Esha"));        friends.put("Dev", List.of("Bala", "Chitra", "Farhan"));        friends.put("Esha", List.of("Chitra"));        friends.put("Farhan", List.of("Dev", "Gita"));        friends.put("Gita", List.of("Farhan"));
        Map<String, Integer> degree = new HashMap<>();        Queue<String> queue = new ArrayDeque<>();        queue.offer("Asha");        degree.put("Asha", 0);
        while (!queue.isEmpty()) {            String person = queue.poll();            System.out.println(person + ": " + degree.get(person) + " step(s) from Asha");            for (String f : friends.get(person)) {                if (!degree.containsKey(f)) {                    degree.put(f, degree.get(person) + 1);                    queue.offer(f);                }            }        }    }}
Output
Asha: 0 step(s) from Asha
Bala: 1 step(s) from Asha
Chitra: 1 step(s) from Asha
Dev: 2 step(s) from Asha
Esha: 2 step(s) from Asha
Farhan: 3 step(s) from Asha
Gita: 4 step(s) from Asha

What this code does

  • The degree map doubles as the visited set: a person gets a degree the moment they are offered, so nobody is queued twice. Dev is reached through Bala first and is not added again through Chitra.
  • The output comes in rings: everyone at 1 step, then 2, then 3. That FIFO order is why each printed number is the shortest distance.

Example 4 · BFS on a grid: shortest path through a campus

CampusPathDemo.javaJava
import java.util.ArrayDeque;import java.util.Arrays;import java.util.Queue;
public class CampusPathDemo {    public static void main(String[] args) {        String[] map = {            "S.#.....",            ".##.###.",            "....#...",            ".##...#E"        };        int rows = map.length;        int cols = map[0].length();        int[][] dist = new int[rows][cols];        for (int[] row : dist) {            Arrays.fill(row, -1);        }
        Queue<int[]> queue = new ArrayDeque<>();        queue.offer(new int[] { 0, 0 });        dist[0][0] = 0;        int[][] moves = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
        while (!queue.isEmpty()) {            int[] cell = queue.poll();            for (int[] m : moves) {                int r = cell[0] + m[0];                int c = cell[1] + m[1];                if (r >= 0 && r < rows && c >= 0 && c < cols                        && map[r].charAt(c) != '#' && dist[r][c] == -1) {                    dist[r][c] = dist[cell[0]][cell[1]] + 1;                    queue.offer(new int[] { r, c });                }            }        }        System.out.println("Steps from S to E: " + dist[rows - 1][cols - 1]);        System.out.println("Steps to the top-right corner: " + dist[0][cols - 1]);    }}
Output
Steps from S to E: 12
Steps to the top-right corner: 11

What this code does

  • Each queue entry is a cell {row, column}. dist is both the answer and the visited mark: -1 means not reached yet, and # cells are walls.
  • BFS reaches E for the first time by a shortest path, so dist at E is the minimum number of steps (moving up, down, left or right).

The steps are short. Put the start in a queue and mark it visited. Then, while the queue is not empty, poll a place and offer each neighbour that has not been visited yet, marking it visited at once. Because the queue is FIFO, nearer places are always handled before farther ones.

This gives BFS its key property: the first time it reaches a place, it has used the fewest possible steps. That is how "degrees of connection" on a social network and the shortest route in a maze are found.

Mark a place visited when you offer it, not when you poll it. Otherwise the same place can enter the queue many times.

Finish up

Mark complete & continue

Next: Must-do problems: Queues and Stacks