class MyQueue {
public:
stack<int>stIn;
stack<int>stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
// 从队列开头移除并返回元素
int pop() {
if(stOut.empty()) // 当stOut为空时,再从StIn中导入数据(导入stIn中的所有数据)
{
while(!stIn.empty())
{
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
// 返回队列的第一个元素
int peek() {
int res = this->pop();
stOut.push(res);
return res;
}
// 返回队列是否为空
bool empty() {
return stIn.empty() && stOut.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();
*/
标签:stIn,int,队列,pop,实现,用栈,stOut,MyQueue,empty
From: https://www.cnblogs.com/dh2021/p/16848293.html