明白队列的性质,然后两个栈,第一个用来进行插入操作,第二个用来进行pop peek操作。条件就是当要进行pop和peek操作,判断第二个栈是不是空,如果是空,把第一个栈的元素移动到第二个里面去。
注意:判空的操作要判断两个栈是不是都为空。因为是两个栈实现队列,所以考虑两个。
class MyQueue {
private:
stack<int> s1;
stack<int> s2;
public:
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
if (s2.empty()){
while (!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
int x = s2.top();
return s2.pop();
return x;
}
int peek() {
if (s2.empty()){
while (!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
int x = s2.top();
return x;
}
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();
*/