两个队列实现一个栈
思路:模拟栈中定义两个队列q1,q2。
push:模拟栈push数据,在q1中push,调用队列q1的push方法
pop:模拟栈pop数据,将q1的数据留出队尾的数据,其余的push到q2中,pop掉q1中剩下的最后一个元素。之后将q2的数据在push到q1中。(需要pop多个数据,需要写循环).
打印:需要像pop一样循环打印
代码:
class Stack
{
public:
void push(const int& x)
{
_qu1.push(x);
}
void pop()
{
if (_qu1.empty())
{
cout << "empty stack!"<<endl;
return;
}
while (_qu1.size() - 1)
{
_qu2.push(_qu1.front());
_qu1.pop();
}
_qu1.pop();
if (_qu1.empty())
{
while (!_qu2.empty())
{
_qu1.push(_qu2.front());
_qu2.pop();
}
}
else
{
assert(false);
}
}
void print()
{
queue<int> tmp1 = _qu1;
queue<int> tmp2= _qu2;
while (tmp1.size())
{
while (tmp1.size() - 1)
{
tmp2.push(tmp1.front());
tmp1.pop();
}
cout << tmp1.front() << "->";
tmp1.pop();
if (tmp1.empty())
{
while (!tmp2.empty())
{
tmp1.push(tmp2.front());
tmp2.pop();
}
}
else
{
assert(false);
}
}
cout << endl;
}
private:
queue<int> _qu1;
queue<int> _qu2;
};以上就是本人在学习过程中的一些经验总结。当然,本人能力有限,难免会有纰漏,希望大家可以指正。
本文出自 “做一个小小小司机” 博客,请务必保留此出处http://10799170.blog.51cto.com/10789170/1763521
原文:http://10799170.blog.51cto.com/10789170/1763521