Stop 10 · Data Structures & Algorithms in JavaTopics · 7/11

Stacks & Queues

Part of the Java Roadmap

In short

Undo buttons, browser back history, bracket checkers, print queues and BFS all rest on two tiny ideas: last in first out, and first in first out.

Stacks (last-in, first-out) and queues (first-in, first-out) solve problems like bracket matching, undo features and level-by-level processing. ArrayDeque implements both in Java.

The jaadu lifts the top plate off a tall wobbly stack of plates while a neat line of people waits at a ticket window behind it.

Think of it like this

Plates and the ticket line

At a wedding buffet, you take the top plate from the stack, the last one the staff put down. Outside at the cinema, the ticket line serves whoever came first. A stack is the plate pile. A queue is the ticket line.

Watch it happen

Checking {[()]} with a stack

push({)
{

Top of the stack is coloured

1/6An opening bracket: push it.

The big ideas

What you need to know

Stack: LIFO

push adds to the top, pop removes from the top, peek looks without removing. All O(1).

Queue: FIFO

offer adds at the back, poll removes from the front, peek looks at the front. All O(1).

Use ArrayDeque

Deque<T> stack = new ArrayDeque<>() and Queue<T> q = new ArrayDeque<>(). The old Stack class is legacy and slower.

Spot the pattern

Matching pairs, undo or 'most recent' means stack. Processing in arrival order or level by level means queue.

See it in code

Walk through the code

java
1import java.util.ArrayDeque;2import java.util.Deque;3import java.util.Map;4import java.util.Queue;5 6public class StackQueueDemo {7    static boolean isBalanced(String s) {8        Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');9        Deque<Character> stack = new ArrayDeque<>();10        for (char c : s.toCharArray()) {11            if (c == '(' || c == '[' || c == '{') {12                stack.push(c);13            } else if (pairs.containsKey(c)) {14                char open = pairs.get(c);15                if (stack.isEmpty() || stack.pop() != open) return false;16            }17        }18        return stack.isEmpty();19    }20 21    public static void main(String[] args) {22        System.out.println(isBalanced("{[()]}"));  // true23        System.out.println(isBalanced("([)]"));    // false24 25        Queue<String> ticketLine = new ArrayDeque<>();26        ticketLine.offer("Asha");27        ticketLine.offer("Vikram");28        System.out.println(ticketLine.poll());     // Asha29    }30}

1/5A map from each closing bracket to its opener, and an ArrayDeque used as a stack.

A bracket checker with a stack, and a first-come-first-served line with a queue. Both use ArrayDeque.

Save yourself the pain

Common mistakes

Oops

Using java.util.Stack.

Do this instead

Stack extends the old synchronized Vector. ArrayDeque is the recommended replacement.

Oops

Comparing two Character objects with == or !=.

Do this instead

That compares references. Unbox to char, as above, or use equals().

Oops

Calling pop() on an empty ArrayDeque.

Do this instead

It throws NoSuchElementException. Check isEmpty() first, or use poll(), which returns null.

Your mission

Stack and queue set

~45 min

Quick check

Your browser's back button should return to the page you visited most recently. Which structure fits?

Go deeper

  1. 1Solve 'valid parentheses' using ArrayDeque as a stack.
  2. 2Implement a queue using two stacks.
  3. 3Solve a 'next greater element' problem with a monotonic stack.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge