利用栈的特性,实现队列
1.栈-后进先出,队列-先进先出,使用两个栈,栈1作用为push数据用,栈2作为pop数据用。
2.原理分析:
1).push数据-当模拟实现的queue push数据往栈1中push。
2).pop数据-判断栈2是否为空,如果栈2为空,则首先将栈1的数据压入到栈2中(依次取栈顶元素push到栈2中),然后pop栈2的栈顶元素。如果,栈2有元素,直接pop栈2的栈顶元素。
3).打印元素
a:栈1和栈2都没有元素--直接返回。
b:栈1有元素且栈2没有元素--将栈1的元素push到栈2中,然后依次打印栈2的元素。
c:栈1没有元素且栈2有元素--直接依次打印栈2的元素。
d:栈1有元素且栈2有元素--首先依此打印栈2的元素(每打印一个元素就pop掉),然后将栈1的元素push到栈2中,然后依次打印栈2的元素。
class Queue //使用的是库中的栈
{
public:
void push(const int& x)
{
_st1.push(x);
}
void pop()
{
if (_st1.empty() && _st2.empty())
{
cout << "empty queue!" << endl;
return;
}
if (!_st2.empty())
{
_st2.pop();
}
else
{
while (!_st1.empty())
{
_st2.push(_st1.top());
_st1.pop();
}
_st2.pop();
}
}
void print()
{
stack<int> tmp1 = _st1; //没有这两句会出bug
stack<int> tmp2 = _st2;
if (_st1.empty() && _st2.empty()) //栈1和栈2都没有元素
{
cout << "empty queue!" << endl;
return;
}
else if ((!_st1.empty()) && _st2.empty()) //栈1有元素且栈2没有元素
{
while (!tmp1.empty())
{
tmp2.push(tmp1.top());
tmp1.pop();
}
while (!tmp2.empty())
{
cout << tmp2.top() << "->";
tmp2.pop();
}
cout << endl;
}
else if (_st1.empty() && (!_st2.empty())) //栈1没有元素且栈2有元素
{
while (!tmp2.empty())
{
cout << tmp2.top() << endl;
tmp2.pop();
}
}
else if ((!tmp1.empty()) && (!tmp2.empty())) //栈1有元素且栈2有元素
{
while (!tmp2.empty())
{
cout << tmp2.top() << endl;
tmp2.pop();
}
while (!tmp1.empty())
{
tmp2.push(tmp1.top());
tmp1.pop();
}
while (!tmp2.empty())
{
cout << tmp2.top() << endl;
tmp2.pop();
}
}
}
private:
stack<int> _st1; //栈1
stack<int> _st2; //栈2
};
以上就是本人在学习过程中的一些经验总结。当然,本人能力有限,难免会有纰漏,希望大家可以指正。
转载于:https://blog.51cto.com/10799170/1763146