//链栈C++描述#includeiostreamusingnamespacestd;structNode{intdata;//数据域Node*next;//指针域};classLinkStack{public:LinkStack();//构造函数,初始化一个空链栈~LinkStack();//析构函数,释放链栈各结点的存储空间voidPush(intx);//入栈操作,将元素x入栈intPop();//出栈操作,将栈顶元素出栈intGetTop();//取栈顶元素(并不删除)intEmpty();//判空操作,判断链栈是否为空栈private:Node*top;//栈顶指针即链栈的头指针};LinkStack::LinkStack(){top=newNode;//生成头结点top-data=0;top-next=NULL;//头结点的指针域置空}LinkStack::~LinkStack(){Node*q=NULL;while(top!=NULL)//释放链栈的每一个结点的存储空间{q=top;//暂存被释放结点top=top-next;//top指向被释放结点的下一个结点deleteq;}q=NULL;}intLinkStack::GetTop(){if(top==NULL)throw"下溢异常";elsereturntop-data;}voidLinkStack::Push(intx){Node*s=NULL;s=newNode;s-data=x;//申请结点s数据域为xs-next=top;top=s;//将结点s插在栈顶}intLinkStack::Pop(){Node*p=NULL;intx;if(top==NULL)throw"下溢";x=top-data;p=top;//暂存栈顶元素top=top-next;//将栈顶结点摘链deletep;returnx;}intLinkStack::Empty(){if(top-next==NULL)return1;elsereturn0;}intmain(){intx,y,z;LinkStackS;//定义链栈变量SS.Push(1);S.Push(2);cout"取栈顶元素"S.GetTop()endl;cout"栈顶元素出栈"S.Pop()endl;if(S.Empty()==1)cout"栈为空"endl;elsecout"栈非空"endl;//栈有2个元素,输出栈非空return0;}
//C语言描述#includestdio.h#includemalloc.h#includestdlib.htypedefstructNode{intdata;structNode*pNext;}NODE,*PNODE;typedefstructStack{PNODEpTop;PNODEpBottom;}STACK,*PSTACK;//PSTACK等价于structSTACK*voidinit(PSTACK);voidpush(PSTACK,int);voidtraverse(PSTACK);boolpop(PSTACK,int*);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);//遍历输出clear(S);//traverse(S);//遍历输出if(pop(S,val)){printf("出栈成功,出栈的元素是%d\n",val);}else{printf("出栈失败!\n");}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;//pS-Bottom-pNext=NULL;}}voidpush(PSTACKpS,intval){PNODEpNew=(PNODE)malloc(sizeof(NODE));pNew-data=val;pNew-pNext=pS-pTop;//pS-Top不能改成pS-BottompS-pTop=pNew;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;elsereturnfalse;}//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参所指向的变量中,如果出栈失败,返回false,否则返回trueboolpop(PSTACKpS,int*pVal){if(empty(pS))//pS本身存放的就是S的地址{returnfalse;}else{PNODEr=pS-pTop;*pVal=r-data;pS-pTop=r-pNext;free(r);r=NULL;returntrue;}}//clear清空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;}}预览时标签不可点收录于话题#个上一篇下一篇