【C语言】顺序栈-基本操作

#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");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值