#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10
typedef struct
{
int data[MAXSIZE];
int top;
}SqStack;
//均通过传递指针的方式传参
void Create();
void Insert(SqStack *s);
void Delete(SqStack *s);
void ViewData(SqStack *s);
>int main()
{
Create(); //初始化顺序栈
return 0;
}
//创建顺序栈栈
void Create()
{
SqStack *s = (SqStack*)malloc(sizeof(SqStack));
int i;
s->top = -1; //标志为-1
for(i = 0; i < MAXSIZE; i ++)
{
s->data[i] = -2; //令所有数据为-2
}
printf("初始化栈完成!\n");
ViewData(s); //遍历栈
Insert(s); //向栈中添加数据
ViewData(s);
Insert(s); //再次调用,向栈中添加数据
Delete(s); //从栈顶删除一个数据
ViewData(s);
s->top = -1; //删除所有数据
free(s); //释放内存
}
//添加数据
void Insert(SqStack *s)
{
int i,num;
if(s->top == (MAXSIZE-1)) //判断是否栈满
printf("当前栈已满,不可添加数据!\n");
else
{
printf("当前栈已有%d个数据,还可添加%d个数据!\n", s->top + 1, MAXSIZE - 1 - s->top);
for(i = s->top + 1; i < MAXSIZE; i ++)
{
printf("请输入想要添加的数据!\n");
scanf("%d", &num); //因为标志初始化时为-1,先自增再使用
if(num != 9999)
s->data[++s->top] = num;
else
break;
}
}
}
//删除数据
void Delete(SqStack *s)
{
int i;
char a;
if(s->top == -1) //通过标志符判断是否为空
printf("当前栈为空,无数据可删除!\n");
else
{
//循环删除,取消删除时跳出
for(i = 0; i <= s->top; i ++)
{
printf("当前栈中共有%d个数据,顶层数据为%d\n请确认是否删除:Y/N !\n",s->top + 1, s->data[s->top]);
scanf("%s", &a);
if(a == 'Y')
s->top --;
else
{
printf("成功取消删除 !\n");
break;
}
}
}
}
//遍历栈中所用数据
void ViewData(SqStack *s)
{
int i;
for(i = 0; i <= s->top; i ++)
{
printf("第%d个数据,值为%d !\n", i + 1, s->data[i]); //直接从数组中读取
}
printf("当前top为%d\n", s->top);
printf("*********************\n");
}
【C语言】顺序栈-基本操作
最新推荐文章于 2022-12-06 16:00:32 发布