此代码可以正确运行,是实实在在的类C语言
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100
typedef int SElemType;
typedef struct
{
SElemType *base; //起始地址
SElemType *top;
int stacksize; //空间大小 eg,a[100]
}SqStack;
enum Status{ERROR,OK};
enum BOOL{FALSE,TRUE};
//顺序栈初始化1
Status InitStack(SqStack &S) //因为是顺序,单向传递,所以必须有& LinkList 不一定有
{
S.base=new SElemType[MAXSIZE]; //申请空间
//S.base = (SElemType *)malloc(MAXSIZE* sizeof(SElemType));
if(!S.base) //申请失败
return ERROR;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
//判断顺序栈是否为空
Status StackEmpty(SqStack S)
{
if(S.top==S.base)
return OK;
else
return ERROR;
}
//求顺序栈的长度
int StackLength(SqStack S)
{
return S.top-S.base; //实际元素
}
//清空顺序栈 --回到初始状态
Status ClearStack(SqStack &S)
{
if(S.base)
S.top=S.base; //强制修改top,因为base始终指向底端
return OK;
}
//销毁顺序栈 1--释放空间
Status DestoryStack(SqStack &S)
{
if(S.base)
{
delete S.base; //free 和malloc,delete 和new
S.stacksize=0;
S.base=S.top=NULL; //重新指向空指针
}
return OK;
}
//销毁栈2
Status StackDestroy(SqStack &S)
{
free(S.base);
S.base = NULL;
S.top = NULL;
S.stacksize = 0;
printf("销毁成功\n");
return OK;
}
//顺序栈进栈
Status Push(SqStack &S,SElemType e)
{
if(S.top-S.base==S.stacksize) //距离==空间 -》栈满
return ERROR;
*S.top=e; //*S.top++=e; 元素e压入栈顶
S.top++; //栈顶指针加1
return OK;
}
//顺序栈出栈
Status Pop(SqStack &S,SElemType &e)
{
if(S.top==S.base) //栈空
return ERROR;
S.top--;
e=*S.top; //e=*--S.top;
return OK;
}
//取顺序栈栈顶元素
Status GetTop(SqStack S,SElemType &e)
{
if(S.top==S.base)
return ERROR; //栈空
e=*(S.top-1); //e=*--S.top;
return OK;
}
main()
{
SqStack S;
typedef int SElemType;
SElemType e;
if(InitStack(S))//枚举类型的接收值为真假
{
for(int i=1;i<5;i++)
{
scanf("%d",&e);
Push(S,e); //指向4上面
}
}
printf("顺序栈长度:%d\n",StackLength(S));
GetTop(S,e);
printf("取栈顶元素:%d\n",e);
while(S.top!=S.base)
{
Pop(S,e);
printf("%d \n",e); //逆置!
}
ClearStack(S);
printf("此时长度为:%d\n",StackLength(S));
StackDestroy(S);
return 0;
}
本文介绍了如何使用C语言实现顺序栈的基本操作,包括初始化、出栈、入栈、销毁、获取栈长、判断栈是否为空以及获取栈顶元素。提供的代码已经过验证,能够正确运行。
1459

被折叠的 条评论
为什么被折叠?



