代码如下:
#include <iostream>
using namespace std;
class ZStackQueue
{
public:
class ZStack
{
public:
ZStack(int size);
~ZStack();
int Pop();
void Push(int e);
bool Empty(){return top == 0;}
private:
int *s;
int top;
int size;
};
public:
ZStackQueue(int n) : s1(n), s2(n){}
void EnQueue(int e);
int DeQueue();
private:
ZStack s1, s2;
};
ZStackQueue::ZStack::ZStack(int n)
: s(0), top(0), size(n)
{
s = new int[size]();
}
ZStackQueue::ZStack::~ZStack()
{
if (s)
{
delete [] s;
s = 0;
}
top = 0;
size = 0;
}
int ZStackQueue::ZStack::Pop()
{
if (top > 0)
return s[--top];
else
return ~0;
}
void ZStackQueue::ZStack::Push(int e)
{
if (top < size)
s[top++] = e;
}
void ZStackQueue::EnQueue(int e)
{
s1.Push(e);
}
int ZStackQueue::DeQueue()
{
if (!s2.Empty())
{
return s2.Pop();
}
else
{
while (!s1.Empty())
s2.Push(s1.Pop());
return s2.Pop();
}
}
int main()
{
ZStackQueue q(3);
q.EnQueue(5);
q.EnQueue(2);
q.EnQueue(8);
cout<<q.DeQueue()<<"/t";//<<q.DeQueue()<<"/t"<<q.DeQueue()<<endl; //如果这样写的话,输出的结果会让你误以为这不是个栈吗,哪是队列呀!呵呵,原因大侠一看都知道的!
cout<<q.DeQueue()<<"/t";
cout<<q.DeQueue()<<"/t";
return 0;
}