
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.
1from collections import deque
2
3class MyStack:
4 def __init__(self):
5 self.q1 = deque()
6 self.q2 = deque()
7
8 def push(self, x: int) -> None:
9 self.q2.append(x)
10 while self.q1:
11 self.q2.append(self.q1.popleft())
12 self.q1, self.q2 = self.q2, self.q1
13
14 def pop(self) -> int:
15 return self.q1.popleft()
16
17 def top(self) -> int:
18 return self.q1[0]
19
20 def empty(self) -> bool:
21 return not self.q1
22This Python implementation uses deque for efficient queue operations. push operations transfer elements between two deques, utilizing the front element of a deque as the stack's top.
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.