What Is a Deque? Double-Ended Queue Explained
You'll learn what a deque is and how it differs from the regular queues you've been using.
Understanding Deque
A deque (pronounced "deck") stands for "double-ended queue." While regular queues follow FIFO semantics—adding at the back and removing from the front—a deque lets you add or remove elements from both ends.
Think of a deque like a deck of cards on a table. With a regular queue, you can only add cards to one end and take from the other. With a deque, you can add or remove cards from either the top or bottom of the deck—complete flexibility at both ends.
Contrasting with Regular Queue
You've seen the Queue interface with methods like offer() (add to back) and poll() (remove from front). A deque extends this capability:
- Add to front or back
- Remove from front or back
- Inspect front or back
This makes deques incredibly versatile. They can function as:
- A regular FIFO queue (use only one-end operations)
- A LIFO stack (use only operations at one end, like push/pop)
- A true double-ended structure (use both ends freely)
The Deque Interface
Java provides the Deque interface (which extends Queue) to represent this data structure. It offers methods like addFirst(), addLast(), removeFirst(), removeLast(), peekFirst(), and peekLast()—giving you explicit control over which end you're working with.
Common implementations include LinkedList (which implements both Queue and Deque) and ArrayDeque.
Key Takeaway: A deque is a double-ended queue that allows insertion and removal at both the front and back, making it more flexible than a regular queue and capable of serving as both a queue and a stack.