Note:
就是用一个栈作为中转,一个是进入,一个是弹出,弹出的为空的时候,把进入的栈里元素全转移过来就好了
代码如下:
class MyQueue {
public:
stack<int> s1, s2;
MyQueue() {
}
void push(int x) {
s2.push(x);
}
int pop() {
if(!s1.empty()){
int a = s1.top();
s1.pop();
return a;
}else{
while(!s2.empty()){
int a = s2.top();
s2.pop();
s1.push(a);
}
int a = s1.top();
s1.pop();
return a;
}
}
int peek() {
if(!s1.empty()){
int a = s1.top();
return a;
}else{
while(!s2.empty()){
int a = s2.top();
s2.pop();
s1.push(a);
}
int a = s1.top();
return a;
}
}
bool empty() {
return s1.empty() && s2.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/