欢迎来到天天文库
浏览记录
ID:37767367
大小:38.50 KB
页数:4页
时间:2019-05-30
《栈的基本结构和操作(C语言实现)》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、#include/*EOF(=^Z或F6),NULL*/#include/*atoi()*/#include#include/*malloc()等*/#include/*eof()*/#include/*exit()*//*函数结果状态代码*/#defineTRUE1#defineFALSE0#defineOK1#defineERROR0#defineINFEASIBLE-1#defineOV
2、ERFLOW-2typedefintStatus;/*Status是函数的类型,其值是函数结果状态代码,如OK等*/typedefintBoolean;/*Boolean是布尔类型,其值是TRUE或FALSE*/typedefintSElemType;//定义栈元素类型//栈的顺序存储表示#defineSTACK_INIT_SIZE12//存储空间初始分配量#defineSTACKINCREMENT2//存储空间分配增量typedefstruct{SElemType*base;//栈底指针,在构造之前和
3、销毁之后,base为NULLSElemType*top;//栈顶指针intstacksize;//当前已分配的栈空间,以元素为单位}SqStack;//-----栈的基本操作-------StatusInitStack(SqStack*S);//构造一个新的栈StatusDestoryStack(SqStack*S);//销毁栈SStatusClearStack(SqStack*S);//把栈S置为空StatusStackEmpty(SqStackS);//判断S是否为空,若为空,返回TRUE,否则返回
4、FALSEintStackLength(SqStackS);//返回S的元素个数,及栈的长度StatusGetTop(SqStackS,SElemType*e);//若栈不为空,用e返回S的栈顶元素,并返回TRUE,否则返回FALSEStatusPush(SqStack*S,SElemTypee);//插入元素e为新的栈顶元素StatusPop(SqStack*S,SElemType*e);//若栈不为空,则删除栈顶元素,并用e返回其值,返回OK,否则返回ERRORStatusStackTraverse
5、(SqStackS,Status(*visit)());//从栈顶到栈底依次对栈中每个元素调用函数visit(),一旦调用visit()失败,则操作失败Statusvisit(SElemTypec);//-------基本操作的算法描述-----------//----------构造一个新的栈StatusInitStack(SqStack*S){(*S).base=(SElemType*)malloc(STACK_INIT_SIZE*sizeof(SElemType));if(!(*S).base)/
6、/存储分配失败exit(OVERFLOW);(*S).top=(*S).base;(*S).stacksize=STACK_INIT_SIZE;returnOK;}//-------销毁栈S,S不再存在StatusDestroyStack(SqStack*S){free((*S).base);(*S).base=NULL;(*S).top=NULL;(*S).stacksize=0;returnOK;}//-------把S置为空栈StatusClearStack(SqStack*S){(*S).top
7、=(*S).base;returnOK;}//----------若栈S为空栈,则返回TRUE,否则返回FALSEStatusStackEmpty(SqStackS){if(S.top==S.base)returnTRUE;elsereturnFALSE;}//---------返回S的元素个数,即栈的长度intStackLength(SqStackS){returnS.top-S.base;}//--------若栈不为空,用e返回S的栈顶元素,并返回TRUE,否则返回FALSEStatusGetTo
8、p(SqStackS,SElemType*e){if(S.top==S.base)returnERROR;*e=*(S.top-1);returnOK;}//---------插入元素e为新的栈顶元素StatusPush(SqStack*S,SElemTypee){if((*S).top-(*S).base>=(*S).stacksize)//满栈,追加存储空间{(*S).base=(SElemType*)realloc((*S).base
此文档下载收益归作者所有