Course contentsShow
← Java
Lesson 1194 of 2,87027. Queue and Deque ImplementationsFree lesson

Deque as Queue and Stack: Dual Behavior

How Deque can function as both a FIFO queue and a LIFO stack, providing unified interface for both data structures.

Deque as Queue and Stack: Dual Behavior

You'll learn how a Deque provides a single interface that can work as both a FIFO queue and a LIFO stack.

The Unified Interface

A Deque (double-ended queue) is remarkably versatile because it lets you add or remove elements from either end. This dual-access capability means one data structure can satisfy two different behavioral patterns:

  • As a Queue (FIFO): Add at the back, remove from the front
  • As a Stack (LIFO): Add and remove from the same end

Think of a Deque like a tunnel with doors at both ends. For queue behavior, people enter through the back door and exit through the front. For stack behavior, everyone uses just one door—last in, first out.

Queue Behavior with Deque

When using a Deque as a queue, you use these methods:

  • offerLast() or offer() — add to the back
  • pollFirst() or poll() — remove from the front
  • peekFirst() or peek() — inspect the front

Stack Behavior with Deque

When using a Deque as a stack, you use these methods:

  • push() — add to the front (like pushing onto a stack)
  • pop() — remove from the front (like popping off a stack)
  • peek() — inspect the front (the top of the stack)

Why This Matters

Instead of maintaining separate Queue and Stack data structures (Java's Stack class is actually legacy and discouraged), you can use a single Deque implementation like ArrayDeque or LinkedList for both purposes. The same underlying data structure adapts to your needs based on which methods you call.

Key Takeaway: A Deque's ability to add and remove from both ends makes it a perfect unified replacement for both Queue (FIFO) and Stack (LIFO) operations, giving you flexibility with a single, efficient data structure.