
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.
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.