//stack.h#include <stdio.h>#include<stdlib.h>#defineTRUE 1#defineFALSE 0#defineOK 1#defineERROR 0#defineOVERFLOW-1#defineUNDERFLOW-2typedefintStatus;typedefintElemtype;structlnode{elemtype data; //data fields structLnode *next;//pointer Field};structlstack{structLnode *top;//stack Top pointer}; Status Initstack (Lstack&s) { structLnode *p; P= (Lnode *)malloc(sizeof(Lnode)); if(!p) exit (ERROR); S.top=p; P->next=NULL; returnOK;} Status Destroystack (Lstack&s) { structLnode *p; P=S.top; while(p) {S.top=p->Next; Free(P); P=S.top; } returnOK;} Status Stackempty (Lstack s) {if(s.top->next==NULL)returnTRUE; returnFALSE;} Status Stacklength (Lstack s) {intLength=0; structLnode *p; P=S.top; while(p->next) {Length++; P=p->Next; } returnlength;} Status Push (Lstack&S,elemtype e) { structLnode *p; P= (Lnode *)malloc(sizeof(Lnode)); if(!p) exit (OVERFLOW); S.top->data=e; P->next=S.top; S.top=p; returnOK;} Status Pop (Lstack&s,elemtype &e) { structLnode *p; if(! (S.top->next))//determine if the stack is empty ·exit (underflow); P=S.top; S.top=p->Next; E=s.top->data; Free(P); returnOK;} Status GetTop (lstack s,elemtype&e) { if(! (s.top->next)) Exit (ERROR); S.top=s.top->Next; E=s.top->data; returnOK;} Status Stacktraverse (Lstack s) {//starting from the top of the stack, sequentially output structLnode *p; if(! (s.top->next)) Exit (ERROR); P=S.top; while(p->next) {P=p->Next; printf ("%d\n",p->data); } returnOK;}intMain () {inte;structLstack S; Initstack (s); Push (S,4); GetTop (s,e); printf ("%d\n", E); printf ("%d\n", Stacklength (s)); Pop (s,e);p rintf ("%d\n", Stackempty (s)); Stacktraverse (s); return 0;}
Chained stack templates