C语言实现栈的基本操作
#include<stdio.h>#include<malloc.h>#include<stdlib.h>#include<stdbool.h>typedefstructNode{intdata;structNode*pNext;}NODE,*PNODE;typedefstructStack{PNODEpTop;PNODEpBottom;}STACK,*PSTACK;//PSTACK等价于structSTACK*voidinit(PSTACK);//初始化栈voidpush(PSTACK,int);//压栈voidtraverse(PSTACK);//遍历boolpop(PSTACKpS,int*pVal);//出栈voidclear(PSTACKpS);//清空栈intmain(void){STACKS;//STACK等价于structStackintval;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\n",val);}else{printf("出栈失败!\n");}*/clear(&S);traverse(&S);return0;}voidinit(PSTACKpS){pS->pTop=(PNODE)malloc(sizeof(NODE));if(NULL==pS->pTop){printf("动态内存分配失败\n");exit(-1);}else{pS->pBottom=pS->pTop;pS->pTop->pNext=NULL;}}voidpush(PSTACKpS,intval){PNODEpNew=(PNODE)malloc(sizeof(NODE));//创建新的节点pNew->data=val;//将val的值赋给新节点的数据域pNew->pNext=pS->pTop;//将新节点的指针域指向下一个节点.pS->Top不能改写成pS->BottompS->pTop=pNew;//pTop指向新节点return;}voidtraverse(PSTACKpS){PNODEp=pS->pTop;while(p!=pS->pBottom){printf("%d",p->data);p=p->pNext;}printf("\n");return;}boolempty(PSTACKpS){if(pS->pTop==pS->pBottom){returntrue;}else{returnfalse;}}boolpop(PSTACKpS,int*pVal){if(empty(pS)){returnfalse;}else{PNODEr=pS->pTop;*pVal=r->data;pS->pTop=r->pNext;free(r);r=NULL;returntrue;}}//清空栈voidclear(PSTACKpS){if(empty(pS))//如果{return;}else{PNODEp=pS->pTop;//定义元素p指向栈顶元素PNODEq=NULL;//定义元素q,初始值为空while(p!=pS->pBottom)//如果栈不为空{q=p->pNext;//q指向p的下一个元素free(p);//释放p所指向的栈顶元素p=q;//将q所指向的元素赋给p}pS->pTop=pS->pBottom;}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。