![](https://i-blog.csdnimg.cn/blog_migrate/d355270bcfc44c6307fffdee388477be.png)
![](https://i-blog.csdnimg.cn/blog_migrate/5957d4d19c46c912fd9ca253dec4a591.png)
思路
用两个队列实现栈,其中一个队列用来存放数据,另一个队列是备用的。
我们仍然拿1,2,3,4,5举例,先将他它们入到pushq中去,这时候由于是模拟栈,我们想出的数据顺序是5,4,3,2,1,所以我们每次出数据是,只在pushq中留下最后一个元素,其余元素转移到popq中去。
![](https://i-blog.csdnimg.cn/blog_migrate/0d6047cb441692a0ab9b3d732bdc483d.png)
转移后:
![](https://i-blog.csdnimg.cn/blog_migrate/e3eeea3cf164a80e8f215f335b909158.png)
然后我们再交换一下pushq与popq。
代码
class MyStack {
public:
MyStack() {
}
void push(int x) {
pushq.push(x);
}
int pop() {
while (pushq.size() > 1)
{
popq.push(pushq.front());
pushq.pop();
}
int ret = pushq.front();
pushq.pop();
swap(pushq, popq);
return ret;
}
int top() {
return pushq.back();
}
bool empty() {
return pushq.empty();
}
private:
queue<int> pushq;
queue<int> popq;
};
进阶
如果理解了用两个队列实现,那么不难发现,其实备用栈是可以省略掉的,我们直接将队列中最后一个元素前面的元素入到队列后面就可以了。
如下图:
![](https://i-blog.csdnimg.cn/blog_migrate/357808b18b611e02bd55f461bc5174eb.png)
进阶代码
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
while (--size)
{
q.push(q.front());
q.pop();
}
int ret = q.front();
q.pop();
return ret;
}
int top() {
return q.back();
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};