栈的基本操作

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define ok 1
#define error 0
#define overflow -1

#define STACK_INIT_SIZE 100   //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间的分配增量
typedef int Status;
typedef int ElemType;

/*栈的顺序存储表示*/
typedef struct{
    ElemType *base;
    ElemType *top;  //栈顶指针
    int stacksize;  //当前已分配的存储空间,以元素为单位
}SqStack;

/*基本操作函数的原型说明*/
Status InitStack(SqStack &S);  //构造空栈S
Status GetTop(SqStack S,ElemType &e);   //返回栈顶元素
Status Push(SqStack &S,ElemType e); //插入e为新的栈顶元素
Status Pop(SqStack &S,ElemType &e); //删除栈顶元素用e返回


/*基本操作的算法实现*/
Status InitStack(SqStack &S)
{
    S.base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
    if(!S.base)
        exit(overflow); //存储分配失败
    S.top=S.base;
    S.stacksize=STACK_INIT_SIZE;
    return ok;
}

Status GetTop(SqStack S,ElemType &e)
{
    if(S.top==S.base)
        exit(overflow);
    e=*(S.top-1);
    return ok;
}

Status Push(SqStack &S,ElemType e)
{
    if(S.top-S.base>=S.stacksize)	//栈满,追加存储结构 
    {
		S.base=(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(ElemType));
		if(!S.base)
			exit(overflow);		//存储分配失败 
		S.top=S.base+S.stacksize;
		S.stacksize+=STACKINCREMENT; 
    }
    *S.top++ =e;
    return ok;
}//push

Status Pop(SqStack &S,ElemType &e)
{
	if(S.top==S.base)
		return error;
	e= *--S.top;
	return ok;
}//Pop

/*简单的测试函数*/
int main()
{
	SqStack S;
	InitStack(S);
	int i,n;
	ElemType e;
	printf("Please input the SqStack's length: ");
	scanf("%d",&n);
	
	printf("\nThe sequence of pushstack is \n");
	for(i=0;i<n;i++)
	{
		Push(S,i*2);
		printf("%d ",i*2);
	}
	printf("\n\n");
	
	printf("The top of stack is \n");
	GetTop(S,e);
	printf("%d\n\n",e);
	
	printf("The sequence of popstack is \n");
	for(i=0;i<n;i++)
	{
		Pop(S,e);
		printf("%d ",e);
	}
	
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值