Dequeue
Deque Interface¶
Think of a train with doors on both ends π
You can board or exit from the front or the back. Thatβs Deque in action.
π§ What is Deque?¶
Deque belongs to the Java Collections Framework
π It stands for Double-Ended Queue π Supports insertion and deletion from both ends
π Key Characteristics¶
- Add/remove from front and rear
-
Can act as:
- Queue (FIFO)
- Stack (LIFO)
- No index-based access
- Faster than legacy
StackandLinkedList(in many cases)
ποΈ Common Implementations¶
1. ArrayDeque (Most Preferred)¶
- Uses resizable circular array
- Very fast β‘
- Does not allow null
2. LinkedList¶
- Doubly linked list
- Allows null
- Slightly slower than
ArrayDeque
βοΈ Important Methods¶
πΉ Insert¶
πΉ Remove¶
πΉ Peek¶
π§ Example¶
Deque<Integer> dq = new ArrayDeque<>();
dq.
addFirst(10); // [10]
dq.
addLast(20); // [10, 20]
dq.
addFirst(5); // [5, 10, 20]
System.out.
println(dq.removeLast()); // 20
System.out.
println(dq);
Output:
π Deque as Queue vs Stack¶
| Behavior | Method Used | Example |
|---|---|---|
| Queue | addLast + removeFirst | FIFO |
| Stack | addFirst + removeFirst | LIFO |
π― Interview Nuggets¶
Dequereplaces Stack (preferred)ArrayDequeis usually faster than LinkedList- No capacity restriction (dynamic)
- Avoid using legacy
Stack
π§ Memory Trick¶
Deque = Queue + Stack (both ends open π)