Deque Operations: Stack and Queue
Use LinkedList as a Deque to implement stack (push/pop) and queue (offer/poll) behavior.
Deque Operations: Stack and Queue is a free Java Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Deque: Double-Ended Queue
A Deque (Double-Ended Queue) allows insertions and removals at both ends. Java's Deque interface is implemented by LinkedList and ArrayDeque.
import java.util.Deque;
import java.util.ArrayDeque;
Deque<String> deque = new ArrayDeque<>();
deque.addFirst("A"); // front
deque.addLast("B"); // back
deque.addFirst("Z"); // new front
System.out.println(deque); // [Z, A, B]ArrayDeque vs LinkedList as Deque
ArrayDeque is generally preferred over LinkedList as a Deque:
- No per-element node overhead
- Better cache locality
- Slightly faster for stack/queue operations
Only choose LinkedList when you also need the List interface.
Stack Operations with Deque
Use push (addFirst) and pop (removeFirst) to simulate a LIFO stack. Avoid the legacy Stack class — it's synchronized and obsolete.
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // 3
System.out.println(stack.peek()); // 2 (no removal)
System.out.println(stack.pop()); // 2Queue Operations with Deque
Use offer (addLast) and poll (removeFirst) to simulate a FIFO queue. offer returns false on failure; add throws.
Deque<String> queue = new ArrayDeque<>();
queue.offer("task1");
queue.offer("task2");
queue.offer("task3");
System.out.println(queue.poll()); // task1
System.out.println(queue.poll()); // task2
System.out.println(queue.size()); // 1Deque Method Reference Table
Deque provides two method families — one that throws exceptions, one that returns special values:
- addFirst/addLast vs offerFirst/offerLast
- removeFirst/removeLast vs pollFirst/pollLast
- getFirst/getLast vs peekFirst/peekLast
Prefer the offer/poll/peek family to avoid exceptions on empty deques.
Real Example: Undo/Redo with Two Stacks
A classic Deque use case: undo history is a stack. Redo is another stack.
Deque<String> undo = new ArrayDeque<>();
Deque<String> redo = new ArrayDeque<>();
undo.push("type 'Hello'");
undo.push("type ' World'");
String action = undo.pop();
System.out.println("Undone: " + action); // type ' World'
redo.push(action);
System.out.println("Redo top: " + redo.peek()); // type ' World'Palindrome Check with Deque
Deques make palindrome checking elegant — compare characters from both ends simultaneously.
Deque<Character> deque = new ArrayDeque<>();
for (char c : "racecar".toCharArray()) deque.add(c);
boolean isPalindrome = true;
while (deque.size() > 1) {
if (!deque.pollFirst().equals(deque.pollLast())) {
isPalindrome = false;
break;
}
}
System.out.println(isPalindrome); // trueBFS with Queue
Breadth-First Search uses a queue. ArrayDeque is the standard choice for BFS in competitive programming and graph traversal.
import java.util.*;
// BFS on a simple adjacency list
Map<Integer,List<Integer>> graph = Map.of(
1, List.of(2,3),
2, List.of(4),
3, List.of(4),
4, List.of()
);
Deque<Integer> queue = new ArrayDeque<>();
Set<Integer> visited = new HashSet<>();
queue.offer(1);
while (!queue.isEmpty()) {
int node = queue.poll();
if (visited.add(node)) {
System.out.print(node + " ");
queue.addAll(graph.get(node));
}
}DFS with Stack
Depth-First Search uses a stack. Again, prefer ArrayDeque over the legacy Stack class.
Deque<Integer> stack = new ArrayDeque<>();
Set<Integer> visited = new HashSet<>();
stack.push(1);
while (!stack.isEmpty()) {
int node = stack.pop();
if (visited.add(node)) {
System.out.print(node + " ");
// push neighbors (will be processed in reverse order)
List<Integer> neighbors = List.of(2, 3); // simplified
for (int n : neighbors) if (!visited.contains(n)) stack.push(n);
}
}Bounded Deque with size check
ArrayDeque grows dynamically, but you can enforce a capacity manually to simulate a bounded buffer:
Deque<Integer> buffer = new ArrayDeque<>();
int MAX = 3;
for (int i = 1; i <= 5; i++) {
if (buffer.size() >= MAX) {
buffer.pollFirst(); // drop oldest
}
buffer.offerLast(i);
}
System.out.println(buffer); // [3, 4, 5]Performance Notes
ArrayDeque uses a circular array that doubles when full. Amortized cost of all operations is O(1). It outperforms LinkedList in most benchmarks due to cache efficiency. Never synchronize manually — use ConcurrentLinkedDeque or a blocking queue for concurrency.
Quick Check
Which class should you prefer over the legacy Stack for LIFO operations?
Recap: Deque Operations
Key takeaways:
- Deque allows O(1) insertions/removals at both ends
- ArrayDeque is preferred over LinkedList for pure stack/queue use
- push/pop → LIFO stack; offer/poll → FIFO queue
- Classic uses: undo/redo, BFS/DFS, sliding window, palindrome check
- Avoid legacy Stack and Queue classes
Frequently asked questions
Is the “Deque Operations: Stack and Queue” lesson free?
Yes — the full text of “Deque Operations: Stack and Queue” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.
What will I learn in “Deque Operations: Stack and Queue”?
Use LinkedList as a Deque to implement stack (push/pop) and queue (offer/poll) behavior. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Java Academy?
No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Deque Operations: Stack and Queue” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Java Academy lesson?
Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- LinkedList Internals
- Deque Operations: Stack and Queue
- LinkedList vs ArrayList Trade-offs
- PriorityQueue for Ordered Processing