欢迎来到天天文库
浏览记录
ID:38499124
大小:33.50 KB
页数:4页
时间:2019-06-13
《栈的基本操作》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include#include#defineOK1#defineERROR0#defineSTACK_INIT_SIZE100//存储空间初始分配量#defineSTACKINCREMENT10//存储空间分配增量typedefintSElemType;//定义栈元素类型typedefintStatus;//Status是函数的类型,其返回值是函数结果状态代码,如OK等structSqStack{SElemType*base;//在栈构造之前和销毁之后,base的值为NULLSElemType*top;//栈顶指针intstacksiz
2、e;//当前已分配的存储空间,以元素为单位};//顺序栈StatusInitStack(SqStack&S)//构造一个空栈S,该栈预定义大小为STACK_INIT_SIZE{S.base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!S.base)returnERROR;S.top=S.base;S.stacksize=STACK_INIT_SIZE;returnOK;}StatusPush(SqStack&S,SElemTypee)//在栈S中插入元素e为新的栈顶元素{if(S.top-S.base>=
3、S.stacksize){S.base=(SElemType*)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(SElemType));if(!S.base)returnERROR;S.top=S.base+S.stacksize;S.stacksize+=STACKINCREMENT;}*S.top++=e;returnOK;}StatusPop(SqStack&S,SElemType&e)//若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR{if(S.top==S.base)returnERR
4、OR;e=*--S.top;returnOK;}StatusGetTop(SqStackS,SElemType&e)//若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR{if(S.top==S.base)returnERROR;e=*(S.top-1);returnOK;}intStackLength(SqStackS){inti;//返回栈S的元素个数if(S.top==S.base)i=0;else{for(i=0;S.base5、栈顶到栈底依次输出栈中的每个元素SElemType*p=(SElemType*)malloc(sizeof(SElemType));p=S.top;//请填空if(p==S.base)printf("TheStackisEmpty!");//请填空else{printf("TheStackis:");p--;while(p>=S.base)//请填空{printf("%d",*p);p--;//请填空}}printf("");returnOK;}intmain(){intquit=0;SqStackS;SElemTypex,e;if(InitStack(S))//判断顺序6、表是否创建成功,请填空{printf("AStackHasCreated.");}while(!quit){inta;printf("1:Push2:Pop3:GettheTop4:ReturntheLengthoftheStack5:LoadtheStack0:ExitPleasechoose:");scanf("%d",&a);switch(a){case1:printf("请输入入栈的值");scanf("%d",&x);if(!Push(S,x)){printf("PushError!");}//判断Push是否合法,请填空else7、{printf("TheElement%disSuccessfullyPushed!",x);}break;case2:if(!Pop(S,e))printf("PopError!");//判断Pop是否合法,请填空elseprintf("TheElement%disSuccessfullyPoped!",e);break;case3:if(!GetTop(S,e))printf("GetTopError!");//判断GetTop是否合法,请填空elseprintf("TheTopEl
5、栈顶到栈底依次输出栈中的每个元素SElemType*p=(SElemType*)malloc(sizeof(SElemType));p=S.top;//请填空if(p==S.base)printf("TheStackisEmpty!");//请填空else{printf("TheStackis:");p--;while(p>=S.base)//请填空{printf("%d",*p);p--;//请填空}}printf("");returnOK;}intmain(){intquit=0;SqStackS;SElemTypex,e;if(InitStack(S))//判断顺序
6、表是否创建成功,请填空{printf("AStackHasCreated.");}while(!quit){inta;printf("1:Push2:Pop3:GettheTop4:ReturntheLengthoftheStack5:LoadtheStack0:ExitPleasechoose:");scanf("%d",&a);switch(a){case1:printf("请输入入栈的值");scanf("%d",&x);if(!Push(S,x)){printf("PushError!");}//判断Push是否合法,请填空else
7、{printf("TheElement%disSuccessfullyPushed!",x);}break;case2:if(!Pop(S,e))printf("PopError!");//判断Pop是否合法,请填空elseprintf("TheElement%disSuccessfullyPoped!",e);break;case3:if(!GetTop(S,e))printf("GetTopError!");//判断GetTop是否合法,请填空elseprintf("TheTopEl
此文档下载收益归作者所有