Elements pushed in order: 10, 20, 30. The front is 10 initially.
Step 2: After first pop()
Pop removes 10, so front becomes 20.
Final Answer:
10\n20 -> Option A
Quick Check:
Queue front after push and pop = 10 then 20 [OK]
Hint: Queue front shows oldest element, pop removes it [OK]
Common Mistakes:
Assuming pop removes from back instead of front
Confusing front() with back()
Printing after pop without updating front
4. Consider this C++ code snippet using queue<int>. It is supposed to print all elements in the queue, but it causes an infinite loop. What is the error?
#include <iostream>
#include <queue>
using namespace std;
int main() {
queue<int> q;
q.push(1);
q.push(2);
q.push(3);
while (!q.empty()) {
cout << q.front() << " ";
// Missing q.pop() here
}
return 0;
}
medium
A. The loop never removes elements, so queue stays non-empty
B. The queue is empty initially, so loop never runs
C. The front() method is used incorrectly
D. The push() method is missing
Solution
Step 1: Analyze the loop behavior
The loop prints front element but never calls pop(), so elements remain in the queue.
Step 2: Understand infinite loop cause
Since queue never empties, q.empty() is always false, causing infinite loop.
Final Answer:
The loop never removes elements, so queue stays non-empty -> Option A