数组实现一个栈,并实现基本功能
#include <iostream>
#include <cstdlib>
using namespace std;
template<typename T>
class ArrayStack
{
public:
ArrayStack(int size)
:arr(NULL)
,len(size)
,top1(0)
,top2(len+1)
{
arr=new T[size+1];
}
~ArrayStack()
{}
bool Empty(int index)//所有的index=0表示操作左栈,index=1操作右栈
{
if (index==0&&top1<1)
{
return true;
}
else if(index==1&&top2>len)
{
return true;
}
else
{
return false;
}
}
void Push(int index,const T& x)
{
if (top1>top2)
return ;
if(index==0)
{
top1++;
arr[top1]=x;
}
else
{
top2--;
arr[top2]=x;
}
}
T Pop(int index)
{
int ret;
if(index==0)
{
if(top1<0)
{
return -1;
}
else
{
ret=arr[top1];
top1--;
}
}
else
{
if(top2>len)
{
return -1;
}
else
{
ret=arr[top2];
top2++;
}
}
return ret;
}
private:
T* arr;
int len;
int top1;
int top2;
};
void test6()
{
ArrayStack<int> as1(6);
as1.Push(0,1);
as1.Push(0,2);
as1.Push(0,3);
as1.Push(0,4);
as1.Push(0,5);
int len=5;
while(len)
{
cout<<as1.Pop(0)<<endl;
--len;
}
cout<<endl;
cout<<endl<<as1.Empty(0)<<endl;
}
void test7()
{
ArrayStack<char> as2(10);
as2.Push(1,'a');
as2.Push(1,'b');
as2.Push(1,'c');
as2.Push(1,'d');
as2.Push(1,'e');
as2.Push(1,'f');
as2.Push(1,'g');
int len=7;
while(len)
{
cout<<as2.Pop(1)<<endl;
--len;
}
cout<<endl;
cout<<endl<<as2.Empty(1)<<endl;
}