数据结构 栈的实现 c语言

//栈的实现c语言
#include <stdio.h>
#include <stdlib.h>
#define LISTSIZE 100
#define LISTCREMENT 10
#define OK 1
#define ERROR 0
typedef struct stack{
	int *base;
	int *top;
	int stack_size;
}stack;
int Init_Stack(stack &s);
int GetTop(stack s,int &e);
int pop(stack &s);
int Push(stack &s,int e); 
int check(stack &s);
int main(void){
	stack a;
	Init_Stack(a);
	int save=0;
	for(int i=5;i>0;i--){
		scanf("%d",&save);
		Push(a,save);
		save=0;
	}
	
	pop(a);
	check(a);
	GetTop(a,save);
} 
int Init_Stack(stack &s){
s.base=(int *)malloc(LISTSIZE*sizeof(stack));
if(!s.base) return ERROR;//malloc error
s.top=s.base;
s.stack_size=LISTSIZE;
return OK;//succeed 
} 
int GetTop(stack s,int &e){
	if(!s.base) return ERROR;//empty
	e=*(s.top-1);
	return OK;
}
int pop(stack &s){
	if(!s.base) return ERROR;//empty

	s.top--;
}
int Push(stack &s,int e){
	if(s.top-s.base>=s.stack_size){
		s.base=(int *)realloc(s.base,(s.stack_size+LISTCREMENT)*sizeof(int));
			if(!s.base) return ERROR;//realloc error
	s.top=s.base+s.stack_size;
	s.stack_size+=LISTCREMENT;
	}

	*(s.top)=e;
	s.top++;
	return OK;
}
int check(stack &s){
	int w;
	while(s.base!=s.top){
     GetTop(s,w);
     printf("%d",w);
     pop(s);
	}
}

猜你喜欢

转载自blog.csdn.net/qq_41105058/article/details/82631536
今日推荐