Problem Description
Implement a last-in-first-out (LIFO) stack using only two queues. The MyStack class should support the following functions:
- push(x): Pushes element x to the top of the stack.
- pop(): Removes the element on the top of the stack and returns it.
- top(): Returns the element on the top of the stack.
- empty(): Returns true if the stack is empty, false otherwise.
Note: Only standard queue operations (push to back, pop from front, size, and is empty) can be used.
Key Insights
- We simulate a stack (LIFO) behavior using two queues (FIFO).
- For the push operation, use one queue (q2) to hold the new element and then transfer all elements from the other queue (q1) to q2 so that the new element is at the front.
- Swap the roles of the two queues after each push so that q1 always holds the stack in the correct order.
- The pop and top operations can then be implemented by simply removing or peeking at the front of q1.
Space and Time Complexity
Time Complexity:
- push: O(n), where n is the number of elements in the stack (due to transferring all elements between queues).
- pop: O(1)
- top: O(1) Space Complexity: O(n), as we store all elements in the two queues.
Solution
We implement the stack using two queues. During each push operation, we enqueue the new element into an empty auxiliary queue (q2) and then move all elements from the primary queue (q1) to q2. This way, the new element comes to the front of the queue, mimicking stack behavior. Finally, we swap q1 and q2 so that q1 always represents the current stack. For pop, we simply dequeue from q1; for top, we peek at the front of q1; and for empty, we check if q1 is empty.
Code Solutions
Below are code solutions in Python, JavaScript, C++, and Java with line-by-line comments.