栈A与栈B模拟队列Q,A为插入栈,B为弹出栈,即A提供入队列功能,B提供出队列功能。实现的方法有获得队列元素大小,判空,获得队头元素
入队列:入栈A
出队列:栈B不为空,直接弹出栈B数据
栈B为空,则弹出栈A的数据,StudyLinkList.h放入栈B中,再弹出栈B的数据
<pre class="cpp" name="code">#include <iostream>
#include <stack>
using namespace std;
template<typename T> //类模版
class QueueByDobuleStack
{
public:
size_t size(); //队列元素大小
bool empty(); //队列判空
void push(T t); //入队列
void pop(); //出队列
T top(); //获得队头元素
private:
stack<T> s1; //栈
stack<T> s2;
};
template <typename T>
size_t QueueByDobuleStack<T>::size()
{
return s1.size()+s2.size();
}
template <typename T>
bool QueueByDobuleStack<T>::empty()
{
return s1.empty()&&s2.empty();
}
template <typename T>
void QueueByDobuleStack<T>::push(T t)
{
s1.push(t);
}
//若栈s2为空,则弹出栈s1的数据,放入栈s2中,再弹出栈s2的数据
//若s2不为空,则直接弹出s2的数据
template <typename T>
void QueueByDobuleStack<T>::pop()
{
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
s2.pop();
}
template <typename T>
T QueueByDobuleStack<T>::top()
{
if (s2.empty())
{
while (!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
int main()
{
QueueByDobuleStack<int> q;
if(q.empty())
printf("p is empty!\n");
for (int i=0;i<10;++i)
{
q.push(i); //测试入队列
}
printf("%d\n",q.size()); //队列元素个数
while(!q.empty())
{
cout<<q.top()<<" "; //获得队头元素
q.pop(); //出队列
}
cout<<endl;
system("pause");
return 0;
}