设置两个栈:一个主栈,一个辅助栈
push新元素的时候,先将主栈依次出栈进栈到辅助栈,再让新元素进到辅助栈,最后将辅助栈所有元素依次出栈进栈到主栈
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
MyQueue() {
}
void push(int x) {
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
s2.push(x);
while(!s2.empty()){
s1.push(s2.top());
s2.pop();
}
}
int pop() {
int x = s1.top();
s1.pop();
return x;
}
int peek() {
return s1.top();
}
bool empty() {
return s1.empty();
}
};
