class MyQueue {
public:
stack<int> stin;
stack<int> stout;
/* push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空。*/
MyQueue() {
}
void push(int x) {
stin.push(x);
}
int pop() {
// 只有当stout为空的时候,再从stin里导入数据(导入stin全部数据)
if (stout.empty()){
while (!stin.empty()){
stout.push(stin.top());
stin.pop();
}
}
int result = stout.top();
stout.pop();
return result;
}
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stout.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
bool empty() {
if (stin.empty() && stout.empty()){
return true;
}
return false;
}
};
/**
* 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();
*/
10-23
678
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-01