#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define MAX_SIZE 5
#define INIT_SIZE 2
typedef int ElemType;
typedef int status;
typedef struct Lnode
{
ElemType *top;//栈顶指针
ElemType *base;//栈底指针
int max;//最大存储量
int size;//实际存储量
}Lnode;//节点类型
//1.栈的初始化
status Init_Stack(Lnode *p)
{
p->base=(ElemType*)malloc(INIT_SIZE*sizeof(ElemType));
if(!p->base)
{
printf("栈初始化失败\n");
exit(0);
}
p->max=INIT_SIZE;
p->size=0;
p->top=p->base;
return OK;
}
//2.入栈
status Push_Stack(Lnode *p,ElemType e)
{
if(p->top-p->base>=p->max)
{
p->base=(ElemType*)realloc(p->base,(MAX_SIZE+p->max)*sizeof(ElemType));
if(!p->base)
return ERROR;
p->top=p->base+p->max;
p->max=MAX_SIZE+p->max;
}
p->size++;
*p->top=e;
p->top++;
return OK;
}
//3.出栈
ElemType Pop_Stack(Lnode *p)
{
ElemType e;
if(p->top==p->base)
{
e=0;
return e;
}
p->size--;
p->top--;
e=*p->top;
return e;
}
int main()
{
Lnode p;
int i,j;
ElemType e;
//1.栈的初始化
Init_Stack(&p);
printf("请输入数据(输入0结束输入)\n");
while(1)
{
scanf("%d",&e);
if(e==0)
break;
Push_Stack(&p,e); //.入栈
}
printf("\n");
while(p.size!=0)
{
e=Pop_Stack(&p); //3.出栈
printf("%d ",e);
}
}
数据结构基础(C语言)———动态顺序栈
最新推荐文章于 2023-11-21 19:27:52 发布