#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
#define Max 20
typedef int ElemType;
typedef struct Stack
{
ElemType* data;// 指示动态分配数组的指针
int top;
int MaxSize;
}Stack;
//初始化
Stack* InitStack(int x)
{
Stack* S = (Stack*)malloc(sizeof(Stack)*x);//申请栈的内存空间,并将空间的地址传给栈数据类型的指针
S->data = (ElemType*)malloc(sizeof(Stack)*x); //开辟栈的数据区
S->MaxSize = x;
S->top = -1;
return S;
}
//入栈
void StackPush(Stack* S,ElemType elem)
{
if(S == NULL)
{
printf("栈不存在\n");
}
else if(S->top+1 == S->MaxSize)
{
printf("栈满\n");
}
S->top++;
S->data[S->top] = elem;
}
//出栈
void StackPop(Stack* S)
{
assert(S);
if(S->top == -1)
{
printf("栈空\n");
}
S->top--;
}
//判断栈是否为空
void StackEmpty(Stack* S)
{
assert(S);
if(S->top == -1)
{
printf("栈空\n");
}
else
{
printf("栈不为空\n");
}
}
//遍历栈
void StackPrint(Stack* S)
{
assert(S);
for(int i=0;i<=S->top;i++)
{
printf(" |%d|\n",S->data[S->top-i]);
}
}
//销毁栈
void StackDestroy(Stack* S)
{
assert(S);
free(S->data);
free(S);
}
int main()
{
ElemType elem;
Stack* S = InitStack(Max);
int status;
while(1)
{
printf("1、入栈 2、出栈 3、判断栈空 4、遍历栈 5、销毁栈 0、结束\n");
scanf("%d",&status);
switch(status)
{
case 1:
printf("请输入想要入栈的值\n");
scanf("%d",&elem);
StackPush(S,elem);
StackPrint(S);
break;
case 2:
StackPop(S);
StackPrint(S);
break;
case 3:
StackEmpty(S);
break;
case 4:
StackPrint(S);
break;
case 5:
StackDestroy(S);
break;
case 0:
exit(-1);
default:
printf("error!\n");
break;
}
}
return 0;
}
顺序栈的基本操作
于 2023-05-25 11:26:51 首次发布