数据结构-栈的基本操作实现

版权声明:欢迎分享(指明出处),若有错误还请指正!!! https://blog.csdn.net/zj19941201/article/details/71215937
/*main*/
#include<stdio.h>
#include<stdlib.h>
#define TRUE		1
#define ERROR		0
#define	OK			1
#define FALSE		0
#define	OVERFLOW	-2
#define STACK_INIT_SIZE		100
#define	STACKINCREMENT		10

typedef int SElemtype;
typedef int Status;

typedef struct{
	SElemtype	*base;
	SElemtype	*top;
	SElemtype	*p;
	int			stacksize;
}SqStack;
#include"zhanhs.h"
main()
{
	SqStack S;
	SElemtype t,u,i=1,j=4;
	InitStack(S);
	for(i=1;i<=j;i++)
	{	printf("入栈元素i=%d\n",i); 
		Push(S,i);
	}
	print(S);
	putchar(10);
	printf("栈顶元素为:%d",GetTop(S,t));//输出栈顶元素
	putchar(10);
	print(S);
	putchar(10);
	int k=0,cnt=2;
	while(k<cnt)
	{
		printf("出栈元素:%d\n",Pop(S,u));
		k++;
	}
		print(S);
		return 0;
}
/*zhanhs.h*/
 Status InitStack(SqStack &S){
	S.base = (SElemtype *)malloc(STACK_INIT_SIZE*sizeof(SElemtype));
	if(!S.base)exit(OVERFLOW);
	S.top=S.base=S.p;
	S.stacksize=STACK_INIT_SIZE;
	return OK;
}

Status Push(SqStack &S,SElemtype e)
{
	if(S.top-S.base>=S.stacksize)
	{S.base=(SElemtype *)realloc(S.base,
						(S.stacksize+STACKINCREMENT)*sizeof(SElemtype));
		if(!S.base)exit(OVERFLOW);
		S.top=S.base+S.stacksize;
		S.stacksize+=STACKINCREMENT; 
	}
	*S.top++=e;
	return OK;
}

Status GetTop(SqStack S,SElemtype &e)
{
	if(S.top==S.base)return ERROR;
	e=*(S.top-1);
	return e;
}

Status Pop(SqStack &S,SElemtype &e)
{
	if(S.top==S.base)return ERROR;
	S.top--;
	e=*S.top;
	return e;
	
}
void print(SqStack S)
{
	while(S.p<S.top)
	{
		printf("%d\t",*S.p);
		S.p++;
	}
}

猜你喜欢

转载自blog.csdn.net/zj19941201/article/details/71215937
今日推荐