栈的基本操作 出栈与入栈

#include<stdio.h>
#include<stdlib.h>
#define LENGTH 100	//初始分配栈的长度
#define ADD_LEN 10	//栈长增量
typedef struct 
{//构造栈的数据类型 
	int *base;
	int *top;
	int stacksize;
}SqStack;
void CreateStack(SqStack &S);//初始化一个栈
void PushStack(SqStack &S,int e);//e进栈
void PopStack(SqStack &S);//栈顶元素出栈
void DestroyStack(SqStack &S);//销毁栈
void PrintfStack(SqStack &S);//输出当前的栈
void main()
{	SqStack Sa;
	int m,n;
	CreateStack(Sa);
	printf("Please input the total of inserting number:");
	scanf("%d",&m);
	while(m>LENGTH)
	{	printf("The number you input can't be larger than %d,please input again:\n",LENGTH);
		scanf("%d",&m);
	}
	while(m--)
	{	printf("Please input a number to insert:");
		scanf("%d",&n);
		PushStack(Sa,n);
	}
	PrintfStack(Sa);
	PopStack(Sa);
	PrintfStack(Sa);
	DestroyStack(Sa);
}
void CreateStack(SqStack &S)
{	S.base=(int *)malloc(LENGTH*sizeof(int));
	if(!S.base)
	{	printf("Fail to create stack!\n");
		return;
	}
	S.top=S.base;
	S.stacksize=LENGTH;
	printf("Success to create stack!\n");
}
void PushStack(SqStack &S,int e)
{	if(S.top-S.base>=S.stacksize)//考虑栈是否已满,如满,则从新分配空间
	{	S.base=(int *)realloc(S.base,(S.stacksize+ADD_LEN)*sizeof(int));
		if(!S.base)
			return;
		S.top=S.base+S.stacksize;
		S.stacksize+=ADD_LEN;
	}
	*S.top++=e;
	printf("%d success to insert the stack!\n",e);
} 
void PopStack(SqStack &S)
{	int m;
	if(S.top==S.base)
	{	printf("The stack is empty!\n");
		return;
	}
	m=*--S.top;
	printf("%d is out of the stack!\n",m);
}
void DestroyStack(SqStack &S)
{	free(S.base);//释放空间
	S.base=NULL;
	*S.top=-1;//将其他成员设置成安全值
	S.stacksize=0;
	printf("Success to destroy the stack!\n");
}
void PrintfStack(SqStack &S)
{	int *p;
	p=S.top;
	printf("The stack is :");
	while(--p>=S.base)
		printf("%d",*p);
	printf("\n");
}

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值