Stacks and Queues
Queue Enqueue/Dequeue
Enqueue values at the back and dequeue them from the front in first-in, first-out order.
Algorithm
The replay uses the same three values in every language, so this Java DSA implementation can be compared directly with the rest of the DSA track.
front
The front is the oldest value still waiting in the queue.
FIFO
A queue removes values in first-in, first-out order.
Visual walkthrough
Basic Implementation
Basic.java
import java.util.*;
public class Basic {
static String render(List<Integer> values) {
StringBuilder out = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
if (i > 0) out.append(" -> ");
out.append(values.get(i));
}
return out.toString();
}
public static void main(String[] args) {
Queue<Integer> queue = new ArrayDeque<>();
for (int value : new int[] {10, 20, 30}) queue.add(value);
List<Integer> removed = new ArrayList<>();
while (!queue.isEmpty()) removed.add(queue.remove());
System.out.println(render(removed));
}
}
Complexity
- Time: O(1) per operation with a real queue
- Space: O(n)
Implementation notes
- Java declares the queue as
Queue<Integer>and backs it withnew ArrayDeque<>(), so operations use the queue interface while storage is an array-backed deque. - The enhanced
forloop reads primitive values fromnew int[] {10, 20, 30}; eachqueue.add(value)appends at the back and boxes theintinto anIntegerfor the generic container. These small boxed values may come from theIntegercache. - Dequeue uses
while (!queue.isEmpty()) removed.add(queue.remove()).remove()takes from the front and would throw on an empty queue, so the guard is the checked empty behavior in this implementation. - The replay-visible FIFO states move from
[10, 20, 30]to[20, 30]and then[], whileremovedgrows to[10, 20, 30]. TheArrayDeque,ArrayList, andStringBuilderoutput are normal JVM heap objects managed while referenced.