
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.
1class MyStack {
2 constructor() {
3 this.q1 = [];
4 this.q2 = [];
5
The JavaScript solution uses arrays to simulate queue operations by leveraging push for enqueue and shift for dequeue functions. Elements are transferred between two arrays to manage stack order.
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.
class MyStack {
std::queue<int> q1;
public:
MyStack() {}
void push(int x) {
q1.push(x);
int size = q1.size();
while (size > 1) {
q1.push(q1.front());
q1.pop();
size--;
}
}
int pop() {
int top = q1.front();
q1.pop();
return top;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};In the C++ version, we use only one queue and rotate elements upon each push to move the newest item to the front, thereby emulating stack behavior efficiently.