
Sponsored
Sponsored
This approach involves using two queues to simulate the operations of a stack. Whenever we push an element onto the stack, we move all elements from the first queue to the second queue, enqueue the new element into the first queue, and then move all elements back from the second queue to the first one. This ensures that the newest element is always at the front of the queue, allowing us to use single dequeue operations for pop() and top(), thus mimicking a stack's LIFO behavior.
Time Complexity: push - O(n), pop, top, and empty - O(1).
Space Complexity: O(n) for two queues storing up to all stack elements at once.
1#include <queue>
2
3class MyStack {
4 std::queue<int> q1, q2;
5public:
6 MyStack() {}
7
8 void push(int x) {
9 q2.push(x);
10 while (!q1.empty()) {
11 q2.push(q1.front());
12 q1.pop();
13 }
14 std::swap(q1, q2);
15 }
16
17 int pop() {
18 int top = q1.front();
19 q1.pop();
20 return top;
21 }
22
23 int top() {
24 return q1.front();
25 }
26
27 bool empty() {
28 return q1.empty();
29 }
30};The C++ implementation uses the STL queue. Elements are pushed into q2, then all elements from q1 are enqueued into q2, and the two queues are swapped to ensure the stack top is always at the front.
This approach only uses one queue to implement the stack. When pushing an element, we enqueue the element and then rotate the queue such that the newly added element reaches the front. The queue thus behaves like a stack with respect to push, pop, top
Time Complexity: push - O(n), pop, top, and empty - O(1).
Space Complexity: O(n), as we use only one queue to hold stack data.
public class MyStack {
private Queue<int> q1;
public MyStack() {
q1 = new Queue<int>();
}
public void Push(int x) {
q1.Enqueue(x);
int count = q1.Count;
while (count > 1) {
q1.Enqueue(q1.Dequeue());
count--;
}
}
public int Pop() {
return q1.Dequeue();
}
public int Top() {
return q1.Peek();
}
public bool Empty() {
return q1.Count == 0;
}
}
This C# implementation successfully creates a stack-like behavior from a single queue by manipulating the order upon each element pushed, sequentially translating this item to the front for stack alignment.