零、说明
- 两栈共用空间是为了解决顺序栈未满时只能利用部分空间的现象,让两个栈分别以数组头部和尾部作为栈底,向中间延伸,直到在中间相遇,即相当于两个栈都满了
- 事实上和顺序栈没什么两样,不过是要新增一个函数参数用于识别在哪个栈进行操作
- 和顺序栈一样,为了在函数中修改结构体内容,函数参数为结构体指针
一、数据类型
typedef struct Doublestack
{
int data[MAXSIZE];
int top1,top2;
}Doublestack;
二、初始化
void Initial(Doublestack *D)
{
D->top1=-1;
D->top2=MAXSIZE;
}
三、入栈出栈
- 入栈
void Push(Doublestack *D,int data,int stackname)
{
if(D->top1!=D->top2-1)
{
if(stackname==1)
{
D->top1++;
D->data[D->top1]=data;
}
else
{
D->top2--;
D->data[D->top2]=data;
}
}
else
{
cout<<"FULL"<<endl;
}
}
- 出栈
int Pop(Doublestack *D,int stackname)
{
int ret;
ret=-1;
if(stackname==1)
{
if(D->top1!=-1)
{
ret=D->data[D->top1];
D->top1--;
}
else
{
cout<<"EMPTY"<<endl;
}
}
if(stackname==2)
{
if(D->top2!=MAXSIZE)
{
ret=D->data[D->top2];
D->top2++;
}
else
{
cout<<"EMPTY"<<endl;
}
}
return ret;
}
- 得到栈顶
int Gettop(Doublestack *D,int stackname)
{
int ret;
if(stackname==1)
{
ret=D->data[D->top1];
}
else
{
ret=D->data[D->top2];
}
return ret;
}
四、使用
int main()
{
Doublestack D;
Initial(&D);
for(int i=1;i<=100;i++)
{
Push(&D,i,1);
Push(&D,1000-i,2);
}
Push(&D,114514,1);
Push(&D,1919810,2);
cout<<Gettop(&D,1)<<' ';
cout<<Gettop(&D,2)<<endl;
for(int i=1;i<=101;i++)
{
cout<<Pop(&D,1)<<' ';
}
cout<<endl;
for(int i=1;i<=100;i++)
{
cout<<Pop(&D,2)<<' ';
}
return 0;
}