#225

Implement Stack using Queues

pupil · 305 · lc easy +21 · 69.4% accepted · 6,897 likes · top 77%

play →

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:

Input
["MyStack", "push", "push", "top", "pop", "empty"]
[[], [1], [2], [], [], []]
Output
[null, null, null, 2, 2, false]

Example 2:

Explanation
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.top(); // return 2
myStack.pop(); // return 2
myStack.empty(); // return False

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24