What if you only had a queue but needed a stack? Here's the clever trick to make it happen!
Why Implement Stack Using Queue in DSA C++?
Imagine you have a stack of plates to wash, but you only have a queue (a line where people wait) to hold them. You want to take the top plate first, but the queue only lets you take the first plate in line. How do you get the last plate you put in?
Using a queue directly to behave like a stack is tricky because queues remove items from the front, not the back. If you try to pick the last item added, you have to move all the other items out of the way first, which is slow and confusing.
By cleverly using one or two queues, we can reorder the items every time we add a new one so that the newest item is always at the front of the queue. This way, removing the top item from the stack is just removing from the front of the queue, making the queue act like a stack.
queue<int> q; q.push(1); q.push(2); // To pop last added, dequeue all except last while(q.size() > 1) { int x = q.front(); q.pop(); q.push(x); } q.pop();
queue<int> q; // On push, rotate queue to keep last added at front q.push(1); int size = q.size(); for(int i = 0; i < size - 1; i++) { q.push(q.front()); q.pop(); } // Now pop is just q.pop();
This technique lets you use a queue to do everything a stack can do, even when you only have a queue available.
Suppose you only have a line system (queue) at a ticket counter but want to serve the most recent customer first (stack behavior). Using this method, you can manage the line to serve the last person who joined first.
Queues remove from front, stacks remove from top (last in).
Rearranging queue after each push simulates stack behavior.
This method helps when only queues are available but stack behavior is needed.
Practice
Solution
Step 1: Understand stack and queue behavior
A stack follows Last-In-First-Out (LIFO), while a queue follows First-In-First-Out (FIFO).Step 2: Simulate stack using queue
By reordering elements in a single queue after each push, the newest element is always at the front, simulating stack pop behavior.Final Answer:
Use one queue and reorder elements to simulate stack behavior -> Option CQuick Check:
Stack via queue = reorder elements [OK]
- Confusing stack with queue behavior
- Using two stacks instead of queues
- Not reordering queue after push
Solution
Step 1: Recall C++ STL queue declaration
The correct syntax uses template syntax: queue<int> q; declares a queue of integers.Step 2: Check syntax correctness
queue<int> q; matches the correct syntax; others have syntax errors or invalid declarations.Final Answer:
queue<int> q; -> Option BQuick Check:
Correct STL queue syntax = queue<int> q; [OK]
- Misplacing template brackets
- Using parentheses instead of semicolon
- Declaring queue as array
class Stack {
queue<int> q;
public:
void push(int x) {
q.push(x);
int n = q.size();
for (int i = 0; i < n - 1; i++) {
q.push(q.front());
q.pop();
}
}
int pop() {
int val = q.front();
q.pop();
return val;
}
};
int main() {
Stack s;
s.push(10);
s.push(20);
s.push(30);
cout << s.pop() << " ";
s.push(40);
cout << s.pop() << " ";
cout << s.pop() << " ";
return 0;
}Solution
Step 1: Trace push operations
Push 10: queue = [10]
Push 20: queue = [20, 10] after rotation
Push 30: queue = [30, 20, 10] after rotationStep 2: Trace pop and push
Pop: returns 30, queue = [20, 10]
Push 40: queue = [40, 20, 10]
Pop: returns 40, queue = [20, 10]
Pop: returns 20, queue = [10]Final Answer:
30 40 20 -> Option AQuick Check:
Stack pop order = 30, 40, 20 [OK]
- Not rotating queue after push
- Confusing queue front with stack top
- Incorrect pop order
class Stack {
queue<int> q1, q2;
public:
void push(int x) {
q1.push(x);
}
int pop() {
if (q1.empty()) return -1;
while (q1.size() > 1) {
q2.push(q1.front());
q1.pop();
}
int val = q1.front();
q1.pop();
swap(q1, q2);
return val;
}
};Solution
Step 1: Analyze pop operation logic
Pop moves all but last element from q1 to q2, then pops last element from q1, then swaps q1 and q2.Step 2: Check correctness of push and pop
Push adds to q1; pop removes last pushed element correctly by transferring elements and swapping queues.Final Answer:
Pop operation is correct; no error -> Option DQuick Check:
Two-queue stack pop logic = correct [OK]
- Swapping queues too early
- Pushing to wrong queue
- Not checking empty queue before pop
Solution
Step 1: Understand time complexity trade-offs
Push elements normally and rotate queue on each pop (push normally, rotate on pop) makes push O(1), pop O(n). Use a queue and a stack together for hybrid implementation is not pure queue. Use two queues to separate push and pop operations uses two queues, not single queue.Step 2: Optimize pop to O(1) with single queue
Enqueue new element, then dequeue and enqueue all previous elements to move new element to front. This makes pop O(1) as front is always top (matches Push elements by enqueueing and dequeueing all elements except the new one).Final Answer:
Push elements by enqueueing and dequeueing all elements except the new one -> Option AQuick Check:
Rotate queue after push for O(1) pop [OK]
- Trying to optimize pop without reordering queue
- Using two queues instead of one
- Mixing stack and queue data structures
Ready to prove it?
Pass the test and this pattern moves unknown
