栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

#include
#include

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353179.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号