数据结构基础(C语言)———动态顺序栈

#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);    
     }    
 } 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值