232. 用栈实现队列
class MyQueue {
public:
MyQueue()
{
}
void push(int x) {
s1.push(x);
}
int pop() {
int ret;
if(!empty()){
if(!s2.empty()){
ret = s2.top();
s2.pop();
return ret;
}else{
while(!s1.empty()){
int temp = s1.top();
s1.pop();
s2.push(temp);
}
ret = s2.top();
s2.pop();
return ret;
}
}
return -1;
}
int peek() {
if(s2.empty()){
while(!s1.empty()){
int temp = s1.top();
s1.pop();
s2.push(temp);
}
}
return s2.top();
}
bool empty() {
return s1.empty() && s2.empty();
}
private:
stack<int> s1;
stack<int> s2;
};