题目描述
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
思路:
栈具有特点后进先出特点,队列具有先进先出的特点,两个栈实现队列,满足以下条件:
- 入数据时,始终保证栈为空
- 出数据时,取非空栈的栈顶元素
具体过程可点链接:https://blog.csdn.net/zhangye3017/article/details/79007463
代码:
#include<iostream>
#include<stack>
using namespace std;
typedef int DataType;
class Queue
{
public:
Queue();
~Queue();
void AppendTail(const DataType& x)
{
s1.push(x);
}
void DeleteHead()
{
if (s2.empty())
{
while (!s1.empty())//如果栈2为空,栈1不为空,将栈1的数据全部移动到栈2中
{
s2.push(s1.top());
s1.pop();
}
}
if (s2.empty())
{
cout << "stack2 is empty" << endl;
}
s2.pop();
}
private:
stack<DataType>s1;
stack<DataType>s2;
};