欢迎来到天天文库
浏览记录
ID:54700792
大小:16.00 KB
页数:4页
时间:2020-04-20
《进出栈操作的算法 3.doc》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、栈操作的算法:#include#include#includetypedefstructNode{intdata;//结点数据域structNode*pNext;//指针域}NODE,*PNODE;typedefstructStack{PNODEpTop;//栈顶PNODEpBottom;//栈底}STACK,*PSTACK;voidinit(PSTACK);//初始化栈voidpush(PSTACK,int);//入栈voidtraverse(PSTACK);//遍历栈boolpop(PSTACK,int*);//出栈voidclea
2、r(PSTACKpS);/清空栈函数声明时形参可以不用写,形参的类型要写intmain(void){STACKS;//S和pS是一个地址intval;init(&S);//造成一个空栈push(&S,1);push(&S,2);push(&S,3);push(&S,4);push(&S,5);push(&S,6);traverse(&S);if(pop(&S,&val))printf("出栈成功,出栈的元素是%d",val);elseprintf("出栈失败!");traverse(&S);clear(&S);printf("元素将被清空!");traverse(&S);retur
3、n0;}voidinit(PSTACKpS){pS->pTop=(PNODE)malloc(sizeof(NODE));if(NULL==pS->pTop){printf("分配内存失败,程序终止!");exit(-1);}pS->pBottom=pS->pTop;pS->pTop->pNext=NULL;return;}voidpush(PSTACKpS,intval){PNODEpNew=(PNODE)malloc(sizeof(NODE));pNew->data=val;pNew->pNext=pS->pTop;pS->pTop=pNew;return;}voidtraverse(P
4、STACKpS){PNODEp=pS->pTop;while(p!=pS->pBottom){printf("%d",p->data);p=p->pNext;}printf("");return;}boolempty(PSTACKpS){if(pS->pBottom==pS->pTop)returntrue;elsereturnfalse;}boolpop(PSTACKpS,int*pVal){if(empty(pS)){returnfalse;}else{PNODEr=pS->pTop;*pVal=r->data;pS->pTop=r->pNext;free(r);r=NULL;retu
5、rntrue;}}voidclear(PSTACKpS){if(empty(pS)){return;}else{PNODEp=pS->pTop;PNODEq=NULL;while(p!=pS->pBottom){q=p->pNext;free(p);p=q;}}pS->pTop=pS->pBottom;//必须有不然是乱数字}
此文档下载收益归作者所有