没想透的一点:对于要实现的队列的pop操作,其实先看输出栈是否为空,如果不为空,直接从输出栈弹出即可,如果为空,再将输入栈的元素依次压入输出栈(注意是全部压入输出栈,毕竟输入栈的最下面的那个元素其实是我们想要弹出的元素),再弹出输出栈的栈顶元素。
卡哥思路讲得很清晰,跟着卡哥代码敲了下:
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
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();
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,队列,pop,int,用栈,empty,stOut,MyQueue,232
From: https://www.cnblogs.com/hisun9/p/18683232