LeetCode Solutions
232. Implement Queue using Stacks
Time: Constructor: $O(1)$, push(x): $O(1)$, pop(): $O(n)$, peek(): $O(n)$, empty(): $O(1)$ Space: $O(n)$
class MyQueue {
public:
void push(int x) {
input.push(x);
}
int pop() {
peek();
const int val = output.top();
output.pop();
return val;
}
int peek() {
if (output.empty())
while (!input.empty())
output.push(input.top()), input.pop();
return output.top();
}
bool empty() {
return input.empty() && output.empty();
}
private:
stack<int> input;
stack<int> output;
};
class MyQueue {
public void push(int x) {
input.push(x);
}
public int pop() {
peek();
return output.pop();
}
public int peek() {
if (output.isEmpty())
while (!input.isEmpty())
output.push(input.pop());
return output.peek();
}
public boolean empty() {
return input.isEmpty() && output.isEmpty();
}
private Deque<Integer> input = new ArrayDeque<>();
private Deque<Integer> output = new ArrayDeque<>();
}
class MyQueue:
def __init__(self):
self.input = []
self.output = []
def push(self, x: int) -> None:
self.input.append(x)
def pop(self) -> int:
self.peek()
return self.output.pop()
def peek(self) -> int:
if not self.output:
while self.input:
self.output.append(self.input.pop())
return self.output[-1]
def empty(self) -> bool:
return not self.input and not self.output