Java ProgramsCollectionsDeque Example

Deque Example in Java

intermediate·  Collections  ·  Queue & Stack

Problem

Deque means double-ended queue — the same instance can be driven with stack-style push()/pop() on one end and queue-style offer()/poll() on the other, without switching data structures.

Use one Deque instance first as a stack, then as a queue, and confirm each behaves correctly.

Input
push(1), push(2), push(3), then offer(4), offer(5)
Output
Stack pop: 3 Queue poll: 2 Final deque: [1, 4, 5]

Java Program

Java
import java.util.Deque; import java.util.LinkedList; public class DequeExample { public static void main(String[] args) { Deque<Integer> deque = new LinkedList<>(); // Used as a stack: push()/pop() both act on the front deque.push(1); deque.push(2); deque.push(3); System.out.println("Stack pop: " + deque.pop()); // Used as a queue: offer() adds to the back, poll() removes from the front deque.offer(4); deque.offer(5); System.out.println("Queue poll: " + deque.poll()); System.out.println("Final deque: " + deque); } }

Output

Stack pop: 3 Queue poll: 2 Final deque: [1, 4, 5]

Core Logic

push() and pop() both operate on the front of the deque, giving stack (LIFO) behavior, while offer() adds to the back and poll() removes from the front, giving queue (FIFO) behavior — both work on the same underlying instance.

How It Works
  1. 1Deque<Integer> deque = new LinkedList<>(); declares the variable by the Deque interface, backed by LinkedList this time.
  2. 2push(1), push(2), push(3) each add to the front, so pop() — which also removes from the front — returns 3, the most recently pushed value.
  3. 3offer(4) and offer(5) add to the back of the deque, which now holds [2, 1, 4, 5].
  4. 4poll() removes from the front — 2, the oldest remaining element — leaving [1, 4, 5].
The same deque instance pops 3 like a stack and then polls 2 like a queue, without ever being reassigned to a different data structure.
💡

Key Point: push()/pop() and offer()/poll() aren't two different objects' worth of behavior — they're two different pairs of method names for operating on the two ends of the exact same Deque.

Complexity
Time Complexity: O(1)Space Complexity: O(n)

Why: LinkedList directly tracks its head and tail nodes, so push(), pop(), offer(), and poll() all run in constant time regardless of how many of the n elements the deque holds.

Key Concepts

Dequepush()/pop() as a stackoffer()/poll() as a queue

Related Programs