![](https://img-blog.csdnimg.cn/img_convert/96afe916a2cf45d29c494787e488fb38.png)
![](https://img-blog.csdnimg.cn/img_convert/e45744e2a4e442308a8d73dd6ad96217.png)
思路
用两个栈实现一个队列,入栈负责入数据,出栈负责出数据。
示例:1, 2, 3, 4, 5,我们将其入到pushST中
![](https://img-blog.csdnimg.cn/img_convert/f57a62e6eede472d941de6d3dcc6d510.png)
出数据时,我们将pushST中的数据入到popST中去
![](https://img-blog.csdnimg.cn/img_convert/eb6d2480d3034f6ab4081e686222b201.png)
popST负责出数据,这样我们入数据顺序是1,2, 3, 4, 5,出数据顺序也是1,2,3,4,5,看起来如同队列一般。
代码
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
pushST.push(x);
}
int pop() {
if (popST.empty())
{
while (!pushST.empty())
{
popST.push(pushST.top());
pushST.pop();
}
}
int ret = popST.top();
popST.pop();
return ret;
}
//注意res复用了pop
//当然不复用pop也可以,只不过我们需要再判空入栈一番,但这样会显得代码冗余繁复。
int peek() {
int res = pop();
popST.push(res);//由于复用导致出栈弹出了元素,我们再将其入回去。
return res;
}
bool empty() {
return pushST.empty() && popST.empty();
}
private:
stack<int> pushST;
stack<int> popST;
};