Deque Example in Java
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.
Java Program
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
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.
- 1
Deque<Integer> deque = new LinkedList<>();declares the variable by the Deque interface, backed by LinkedList this time. - 2
push(1),push(2),push(3)each add to the front, sopop()— which also removes from the front — returns3, the most recently pushed value. - 3
offer(4)andoffer(5)add to the back of the deque, which now holds[2, 1, 4, 5]. - 4
poll()removes from the front —2, the oldest remaining element — leaving[1, 4, 5].
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.
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.