
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.
Java implementation utilizes a single LinkedList as a queue. The push operation enhances the stack properties by queue management, positioning the latest addition at the front.