Implement Stack using Queues
pupil · 305 · lc easy +21 · 69.4% accepted · 6,897 likes · top 77%
Description
Build a LIFO (last-in-first-out) stack using only two queues as the underlying data structure. The stack must support four operations: push, pop, top, and empty.
Implement the MyStack class:
- void push(int x) Adds element x to the top of the stack.
- int pop() Removes and returns the top element.
- int top() Returns the top element without removing it.
- boolean empty() Returns true when the stack is empty, false otherwise.
Constraints:
- Only standard queue operations are permitted: enqueue to back, peek/dequeue from front, size check, and empty check.
- If your language lacks a native queue, a list or deque used strictly as a queue is acceptable.
Example 1:
Example 2:
Code