C语言—栈

#include <stdio.h>
#include <stdlib.h>
#define STACK_INIT_SIZE 100		//存储空间初始分配量
#define STACKINITCREMENT 10		//存储空间分配增量

typedef	int SElemType;
typedef struct {
	SElemType *base;	//栈底指针-空栈时为 NULL 
	SElemType *top;		//栈顶指针 
	int	stacksize;		//当前已分配的存储空间 
}SqStack;

void	InitStack(SqStack &S,SElemType e) {		//构造一个栈 
	int num;
	S.base = (SElemType *)malloc(STACK_INIT_SIZE *sizeof(SElemType));
	if(!S.base) {
		printf("构造栈失败,程序退出!");
		exit(!0);
	}
	S.top = S.base;		//栈顶指针指向栈底 
	S.stacksize = STACK_INIT_SIZE;	//栈当前的长度
	printf("请输入栈的长度:");
	scanf("%d",&num);
	for(int i=1;i <= num;i++)
	{
		printf("请输入栈的第%d个元素:",i);
		scanf("%d",&e);
		*S.top++ = e;
	}
}

void	GetTop(SqStack S,SElemType &e) {	//获取栈顶元素 
	if(S.top == S.base) {
		printf("空栈,获取无效,程序退出!");
		exit(!0);
	} 
	e = *(S.top -1);
	printf("\n当前栈顶元素为:%d\n",e);
}

void	Push(SqStack &S,SElemType e) {	//插入元素 
	if(S.top - S.base >= S.stacksize) {	//如栈满,则扩展栈的空间 
		S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINITCREMENT)*sizeof(SElemType));
		if(!S.base) {
			printf("空间扩展失败,程序退出!");
			exit(!0);
		}
		S.top = S.base + S.stacksize;
		S.stacksize += STACKINITCREMENT;
	}
	printf("\n\n请输入插入栈的元素:");
	scanf("%d",&e);
	*S.top++ = e;
}

void	Pop(SqStack &S,SElemType &e) {	//出栈操作 
	if(S.top == S.base) {
		printf("\n当前栈为空栈,无法执行出栈操作,程序退出!\n");
		exit(!0);
	}
	e = *--S.top;
	printf("\n出栈元素为:%d\n",e);
}

void	Printf(SqStack &S) {	//遍历栈内元素 
	SqStack elem = S;
	printf("栈内元素:");
	while(elem.base != S.top) {
		printf("%4d",*(elem.top-1));
		*elem.top--;
		elem.base++;
	}
}

int main() {
	SqStack S;
	SElemType e;
	
	InitStack(S,e);		//创建一个栈并
	printf("\n");
	Printf(S); 			//输出栈内元素 
	
	GetTop(S,e);		//获取栈顶元素 
	Pop(S,e);			//出栈操作 
	Printf(S);			//输入当前栈内元素
	 
	Push(S,e);			//入栈操作 
	Printf(S);			//输入当前栈内元素 

	return 0;
}

猜你喜欢

转载自blog.csdn.net/Long_UP/article/details/121767023