194. Implement Stack using Queues
Easy · Stack
Implement a Last-In-First-Out (LIFO) stack data structure using only queue(s). A queue is a First-In-First-Out (FIFO) data structure.
You must implement the Stack class with the following methods: - `push(x)`: Push element x onto the stack. - `pop()`: Remove and return the top element of the stack. - `top()`: Return the top element without removing it. - `empty()`: Return true if the stack is empty, false otherwise.
You may use a standard queue implementation (array with shift/unshift or similar).
Examples
Example 1 Input: Operations: push(1), push(2), top(), pop(), empty() Output: Results: null, null, 2, 2, false Explanation: After pushing 1 and 2, top() returns 2 (the most recently added). pop() removes and returns 2. empty() returns false because 1 is still in the stack.
Example 2 Input: Operations: push(5), push(10), pop(), pop(), empty() Output: Results: null, null, 10, 5, true Explanation: Push 5 then 10. Pop returns 10 (LIFO), then pop returns 5. Stack is now empty.
Constraints
- Standard input/output constraints apply