双向栈程序设计

2025-03-07 04:47:13
推荐回答(1个)
回答1:

//你这个太乱了,我在你这个的基础之上写了一下,你自己对照下,看有没有帮助,你在定义双向栈的时候就出了点问题。双向栈是由两个指针(下标一标识);在这个题我用的是top和base;按照提示输入应当是没什么问题的,//请问楼主有什么具体要求,
#include
#include
#include

#define Elemtype int
#define OK 1
#define OVERFLOW 0
#define ERROR 0

typedef struct fjs
{
Elemtype *a;
int top;
int base;
}BDStacktype;//定义双向栈
class Status
{ int m ,i;
Elemtype x;
BDStacktype tws;

public:
int Init_Stack(BDStacktype *tws,int m);
int push(BDStacktype *tws,int i,Elemtype x);
int pop(BDStacktype *tws,int i,int M);

};

int Status::Init_Stack(BDStacktype *tws,int m)//初始化一个大小为m的双向栈tws
{
tws->a=(Elemtype *)malloc(m*sizeof(Elemtype ));
tws->top=-1;tws->base=m;//
return OK;
}//Init_Stack

int Status::push(BDStacktype *tws,int i,Elemtype x)//x入栈,i=0表示低端栈,i=1表示高端栈
{
if(tws->top+1==tws->base)//注意此时的栈满条件
return OVERFLOW;
if(i==0)
{tws->top++;tws->a[tws->top]=x;}
else
{tws->base--; tws->a[tws->base]=x;}
return OK;
}//push

int Status::pop(BDStacktype *tws,int i,int M)//x出栈,i=0表示低端栈,i=1表示高端栈
{
if(i==0)
{
if(tws->top==-1)
{printf("this is a empty zhan.\n");return OVERFLOW;}
else
{
while(tws->top!=-1)
{
printf("%d ",tws->a[tws->top]);//输出出栈元素。
tws->top--;
}
printf("\n");
}
}
else
{
if(tws->base==M)
{printf("this is a empty zhan\n");return OVERFLOW;}
else
{
while(tws->base!=M)
{
printf("%d ",tws->a[tws->base]);
tws->base++;
}
printf("\n");
}
}
}//pop
void main()
{
int m;
int i;
Elemtype x;
BDStacktype tws;//定义一个栈

Status mystatus;
int a;
do{
printf("*****************************************************\n");
printf("1.初始化一个大小为m的双向栈tws\n");
printf("2.入栈操作\n");
printf("3.x出栈操作\n");
printf("4.退出操作\n");
printf("*****************************************************\n");
re:
printf("请输入您要执行操作的序号:");
scanf("%d",&a);
switch(a)
{
case 1:printf("please input the size of the zhan :");scanf("%d",&m);mystatus.Init_Stack( &tws,m);break;
case 2:printf("please input the element of the and the high<1> or low<0>:");scanf("%d%d",&x,&i);mystatus.push(&tws,i,x);break;
case 3:printf("please input the high<1> or low<0> and the size of the zhan:");scanf("%d%d",&i,&m);mystatus.pop(&tws,i,m);break;//
case 4:exit(0);break;
default:printf("\nThe choice is between 1 to 4.\n");goto re;
}
}while(a!=0);
}