Header file
1typedefintElementType;2 3 #ifndef _stackli_h_4 #define_stackli_h_5 6 structNode;7typedef Node *Ptrtonode;8 typedef ptrtonode Stack;9 Ten intIsEmpty (Stack S); OneStack Createstack (void); A voidDisposestack (Stack S); - voidmakeempty (Stack S); - voidPush (ElementType X, Stack S); the ElementType Top (Stack S); - voidPop (Stack S); - - #endif
source file
1#include"stackli.h"2#include <malloc.h>3#include <stdlib.h>4 5 structNode6 {7 ElementType Element;8 Ptrtonode Next;9 };Ten One intIsEmpty (Stack S) A { - returnS->next = =NULL; - } the - //Create the head node of the stack -Stack Createstack (void) - { +Stack S = (stack)malloc(sizeof(structNode)); - if(S = =NULL) + { Afprintf (stderr,"%s\n","Out of space!!!"); atExit (-1); - } -S->next =NULL; - returnS; - } - in //destroying stacks (including head nodes) - voidDisposestack (Stack S) to { + Makeempty (S); - Free(S); the } * $ //emptying the stack is all the data pops up .Panax Notoginseng voidmakeempty (Stack S) - { the if(S = =NULL) + { Afprintf (stderr,"%s\n","must use Createstack first"); theExit (-1); + } - Else $ while( !IsEmpty (S)) $ Pop (S); - } - the //into the stack, after inserting the head node - voidPush (ElementType X, Stack S)Wuyi { thePtrtonode Tmpcell = (ptrtonode)malloc(sizeof(structNode)); - if(Tmpcell = =NULL) Wu { -fprintf (stderr,"%s\n","Out of space!!!"); AboutExit (-1); $ } - Else - { -Tmpcell->element =X; ATmpcell->next = s->Next; +S->next =Tmpcell; the } - } $ the //returns the top element of the stack, noting that s cannot be empty the ElementType Top (Stack S) the { the if(IsEmpty (S)) - { infprintf (stderr,"%s\n","Empty Stack"); the return-1; the } About Else the returnS->next->Element; the } the + //out of the stack, delete the successor of the head node - voidPop (Stack S) the {Bayi if(IsEmpty (S)) the { thefprintf (stderr,"%s\n","Empty Stack"); - } - Else the { thePtrtonode P = s->Next; theS->next = p->Next; the Free(P); - } the}
Test file
1#include <stdio.h>2#include"stackli.h"3 4 Main ()5 {6 Stack S;7 inti;8 9S =Createstack ();Ten for(i =0; I <Ten; i++ ) One Push (i, S); A - while( !IsEmpty (S)) - { theprintf"%d", Top (S)); - Pop (S); - } - + Disposestack (S); - return 0; +}
[Data structure and algorithm]: The chain implementation of the stack