用两个栈实现一个队列:算法示意图如下
#include <iostream>
using namespace std;
const int StackSize = 100; //栈容量
template<class T>
class SeqStack
{
public:
SeqStack(){ top = -1;}
~SeqStack(){}
void Push(T x);
bool IsEmpty();
T Pop();
int top;
private:
T data[StackSize];
};
template<class T>
bool SeqStack<T>::IsEmpty()
{
if(top == -1)
{
return true;
}
else
{
return false;
}
}
template <class T>
void SeqStack<T>::Push(T x)
{
if (top == StackSize-1)
{
cout << "队满" <<'\n';
exit(0);
}
else
{
top++;
data[top] = x;
}
}
template <class T>
T SeqStack<T>::Pop()
{
T x;
if (top == -1)
{
cout << "队空" <<'\n';
exit(0);
}
else
{
x = data[top--];
return x;
}
}
template <class T>
class Queue
{
public:
void EnQueue(T x);
T DeQueue();
private:
SeqStack<T> s1; //作为存储空间
SeqStack<T> s2; //作为缓冲区
};
template<class T>
void Queue<T>::EnQueue(T x)
{
T n;
if(s1.IsEmpty() && !s2.IsEmpty()) //倒栈将s2的元素倒入s1
{
while(s2.top != -1)
{
n = s2.Pop();
s1.Push(n);
}
s1.Push(x);
}
else //s1不为空则直接将x压入栈
{
s1.Push(x);
}
}
template<class T>
T Queue<T>::DeQueue()
{
T x;
if(s1.IsEmpty() && !s2.IsEmpty()) //s1为空s2不为空直接出栈
{
return s2.Pop();
}
else if(!s1.IsEmpty()) //s1不为空则将s1倒入s2
{
while(s1.top != 0)
{
x = s1.Pop();
s2.Push(x);
}
return s1.Pop();
}
else
{
return s1.Pop();
}
}
int main()
{
Queue<int> a;
/*cout << a.DeQueue() << '\n';*/
a.EnQueue(100);
a.EnQueue(101);
a.EnQueue(102);
cout << a.DeQueue() << '\n';
cout << a.DeQueue() << '\n';
a.EnQueue(103);
a.EnQueue(104);
cout << a.DeQueue() << '\n';
cout << a.DeQueue() << '\n';
return 0;
}