顺序栈的基本操作
1、初始化
2、插入
3、查找
4、遍历
5、清空
6、长度
7、销毁
#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define MAXSIZE 100
typedef int Status;
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
//初始化
Status InitStack(SqStack *S)
{
S->base=(SElemType*)malloc(sizeof(SElemType));
if(!S->base) return ERROR;
S->top=S->base;
S->stacksize=MAXSIZE;
return OK;
}
//进栈
Status PushStack(SqStack *S)
{
int i,length;
SElemType e;
if(S->top-S->base==S->stacksize) return ERROR;
printf("要压入多少个元素:");
scanf("%d",&length);
printf("输入要压入的元素:\n");
for(i=1;i<=length;i++)
{ scanf("%d",&e);
*S->top++=e;
}
return OK;
}
//出栈
Status PopStack(SqStack *S)
{
SElemType e;
if(S->top==S->base) return ERROR;
while(S->top!=S->base)
{
e=*--S->top;
printf("%d ",e);
}
printf("\n");
return OK;
}
//判断是否为空栈
int StackEmpty(SqStack *S)
{
if(S->base==S->top) printf("栈为空!\n");
else
printf("栈不为空!\n");
}
//清空栈
Status ClearStack(SqStack *S)
{
if(S->base)
S->top=S->base;
return OK;
}
//销毁栈
Status DestroyStack(SqStack *S)
{
if(S->base)
{
free(S->base);
S->stacksize=0;
S->top=S->base=NULL;
}
return OK;
}
//获取栈顶元素
Status GetStack_T(SqStack *S)
{
if(S->top!=S->base)
return *(S->top-1);
}
Status Stacklength(SqStack S)
{
return (S.top-S.base);
}
int main()
{
int i,j,select;
SqStack S;
printf("*********************************\n");
printf("1、建立栈 2、压入元素\n3、输出栈的元素 4、判断栈是否为空\n5、销毁栈 6、清空栈\n7、获取栈顶元素 8、获取栈的长度\n0、退出\n");
printf("*********************************\n");
while(1)
{
printf("请输入选择:");
scanf("%d",&select);
if(select==0) break;
switch(select)
{
case 1://1、建立栈
{
i=InitStack(&S);
if(i==1)
printf("建立成功!\n");
else if(i==0) printf("建立失败!\n");
}break;
case 2://2、压入元素
{
i=PushStack(&S);
if(i==1) printf("压入成功!\n");
else if(i==0) printf("栈满压入失败!\n");
}break;
case 3://3、输出栈的元素
{
i=PopStack(&S);
if(i==1) printf("弹出成功!\n");
else if(i==0) printf("栈空弹出失败!\n");
}break;
case 4://4、判断栈是否为空
{
StackEmpty(&S);
}break;
case 5://5、销毁栈
{
i=DestroyStack(&S);
if(i==1) printf("销毁成功!\n");
}break;
case 6://6、清空栈
{
i=ClearStack(&S);
if(i==1) printf("清空成功!\n");
}break;
case 7://7、获取栈顶元素
{
i=GetStack_T(&S);
printf("栈顶元素是:%d",i);
printf("\n");
}break;
case 8://8、获取栈的长度
{
i=Stacklength(S);
printf("栈当前长度为:%d\n",i);
}
}
}
}