Imagine you have tasks arriving in order and you want to process them in the same order they came. Why is a queue better than a stack for this?
Think about how you line up in a queue at a store versus stacking plates.
A queue follows first-in, first-out (FIFO) order, so tasks are handled in the order they arrive. This is important for fairness and correctness in scheduling. A stack uses last-in, first-out (LIFO), which reverses order and is not suitable here.
Consider this Java queue code using integers. What is printed after the operations?
import java.util.LinkedList; import java.util.Queue; public class QueueExample { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(10); q.add(20); q.add(30); q.remove(); q.add(40); System.out.println(q); } }
Remember that remove() takes out the first element added.
The queue starts with 10, 20, 30. remove() deletes 10 (the first). Then 40 is added at the end. The queue now has 20, 30, 40.
Look at this Java code snippet. Why does it cause an error?
import java.util.Queue; import java.util.LinkedList; public class TestQueue { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); q.add(1); q.add(2); int x = q.peek(); System.out.println(x); int y = q.remove(); System.out.println(y); int z = q.remove(); System.out.println(z); int w = q.remove(); System.out.println(w); } }
Check what happens when you remove from an empty queue.
The queue has two elements: 1 and 2. After removing twice, the queue is empty. The third remove() call tries to remove from empty queue, causing NoSuchElementException.
This Java code simulates a simple producer adding numbers and a consumer removing them from a queue. What is printed?
import java.util.LinkedList; import java.util.Queue; public class ProducerConsumer { public static void main(String[] args) { Queue<Integer> q = new LinkedList<>(); for (int i = 1; i <= 3; i++) { q.add(i); System.out.print("Produced " + i + ", "); } while (!q.isEmpty()) { int val = q.remove(); System.out.print("Consumed " + val); if (!q.isEmpty()) System.out.print(", "); } } }
Remember the queue processes items in the order they were added.
The producer adds 1, 2, 3 in order. The consumer removes them in the same order (FIFO). So output shows produced 1,2,3 then consumed 1,2,3.
In graph traversal, why is a queue used in BFS instead of a stack?
Think about how BFS explores nodes closest to the start before going deeper.
BFS uses a queue to visit nodes in order of their distance from the start node. This level-by-level exploration is possible because the queue processes nodes in FIFO order.
