# include<stdio.h># include<malloc.h># include<stdlib.h>typedefstructnode{intdata; structNode *Pnext;} NODE,*Pnode;typedefstructstack{Pnode ptop; Pnode Pbottm;} STACK,*Pstack;voidInitstack (Pstack pS);voidPushstack (Pstack PS,intval);voidTraversestack (Pstack pS);BOOLPopstack (Pstack PS,int*pVal);BOOLempty (Pstack PS);voidClearstack (Pstack pS);intMainvoid) {STACK s; printf ("%p\n", s); intVal; Initstack (&s);//The goal is to create an empty stackPushstack (&s,1); Pushstack (&s,2); Pushstack (&s,3); Pushstack (&s,4); Pushstack (&s,5); Traversestack (&s); if(Popstack (&s,&val)) {printf ("The stack succeeds, the elements of the stack are%d\n", Val); } Else{printf ("the stack failed \ n"); } traversestack (&s); Clearstack (&s); Traversestack (&s); if(Popstack (&s,&val)) {printf ("The stack succeeds, the elements of the stack are%d\n", Val); } Else{printf ("the stack failed \ n"); } return 0;}voidInitstack (pstack PS) {PS->ptop= (Pnode)malloc(sizeof(NODE)); if(ps->ptop==NULL) {printf ("dynamic memory allocation failed! \ n"); Exit (-1); } Else{PS->pbottm=ps->ptop;//ps->pbottm->pnext=ps->ptop->pnext?ps->ptop->pnext=NULL; }}voidPushstack (Pstack PS,intval) {Pnode pnew= (Pnode)malloc(sizeof(NODE)); Pnew->data=Val; Pnew->pnext=ps->ptop;//because the first ptop and Pbottom point are the same node, so Ps->ptop=ps->pbottomps->ptop=pnew; return;}voidTraversestack (Pstack pS) {Pnode P=ps->Ptop; while(P!=ps->Pbottm) {printf ("%d",p->data); P=p->Pnext; } printf ("\ n"); return;}BOOLempty (Pstack PS) {if(ps->ptop==ps->Pbottm)return true; Else return false;}//The stack that points to the PS is stacked once and the elements of the stack are stored in the variable pointed to by the PVal parameter, if the stack fails, returns FALSE, otherwise trueBOOLPopstack (Pstack PS,int*pVal) { if(Empty (PS))//PS itself holds the address of S. { return false; } Else{Pnode R=ps->ptop;//To release that piece of memory .*pval=r->data; PS->ptop=r->Pnext; Free(R); R=NULL; return true; }}//ClearvoidClearstack (Pstack pS) {if(Empty (PS)) {return; } Else{Pnode P=ps->Ptop; Pnode Q=NULL; while(P!=ps->Pbottm) {Q=p->Pnext; Free(P); P=Q; } PS->ptop=ps->Pbottm; }}
Data structure (stack operation) C language implementation