232. 用栈实现队列
class MyQueue:
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x: int) -> None:
self.stack1.append(x)
def pop(self) -> int:
r = self.peek()
self.stack2.pop()
return r
def peek(self) -> int:
if self.stack2:
return self.stack2[-1]
if not self.stack1: return -1
while self.stack1:
self.stack2.append(self.stack1.pop())
return self.stack2[-1]
def empty(self) -> bool:
return not self.stack1 and not self.stack2

class MyQueue {
stack<int> stackIn, stackOut;
public:
MyQueue() {
}
void push(int x) {
stackIn.push(x);
}
int pop() {
int r = this->peek();
stackOut.pop();
return r;
}
int peek() {
if (!stackOut.empty()){
return stackOut.top();
}
if (stackIn.empty()){
return -1;
}else{
while (!stackIn.empty()){
stackOut.push(stackIn.top());
stackIn.pop();
}
return stackOut.top();
}
}
bool empty() {
return stackIn.empty() && stackOut.empty();
}
};