
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.
1import java.util.LinkedList;
2import java.util.Queue;
3
4class MyStack {
5 Queue<Integer> q1 = new LinkedList<>();
6 Queue<Integer> q2 = new LinkedList<>();
7
8 public void push(int x) {
9 q2.add(x);
10 while (!q1.isEmpty()) {
11 q2.add(q1.remove());
12 }
13 Queue<Integer> temp = q1;
14 q1 = q2;
15 q2 = temp;
16 }
17
18 public int pop() {
19 return q1.remove();
20 }
21
22 public int top() {
23 return q1.peek();
24 }
25
26 public boolean empty() {
27 return q1.isEmpty();
28 }
29}
30The Java code uses the LinkedList as a queue. Similar to the C++ solution, elements are rearranged to maintain the stack order by swapping queues after each push operation.
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.
1
This approach takes advantage of a single queue, rotating the elements until the newly pushed element reaches the front. This ensures it behaves as the top of the stack.