This stack is a stack with a table header. Implementation of the stack of some specification operations, initialization, insertion, deletion and so on. Includes two header file Stack.h,fatal.h, library function stack.c, test function teststack.c. The header file is the function declaration, the library function stack.c The function of the definition.
Stack.h
typedefintElementType, #ifndef _stack_h#include<stdbool.h>structNode;typedefstructNode *ptrtonode;typedef Ptrtonode Stack;BOOLIsEmpty (Stack S);//determine if the stack is emptyStack Creatstack (void);//Initialize a stackvoidPop (Stack S);//the stack is deleted, only the top element of the stack pops upvoidMakeempty (Stack S);//make a stack emptyvoidPush (ElementType X, Stack S); ElementType Top (Stack S);voidDisposestack (Stack S);voidPrintstake (Stack S);#endif //!_stack_h
Fatal.h
#include <stdio.h>#include<stdlib.h>#define Error (str) fatalerror (str)#define fatalerror (str) fprintf (stderr, "%s\n", Str), exit (1);
Stack.c
#include"Stack.h"#include<stdlib.h>#include<stdio.h>#include"fatal.h"//definition of structural bodystructnode{ElementType Element; Ptrtonode Next;};BOOLIsEmpty (Stack S) {returnS->next = =NULL;}//Initialize a stackStack Creatstack (void) {Stack S; S=malloc(sizeof(structNode)); if(S = = NULL) FatalError ("Out of space!") S->next =NULL; Makeempty (S);//guaranteed stack is an empty stack returnS;}//Delete the stack and delete the top element onlyvoidPop (Stack S) {Ptrtonode FirstCell; if(IsEmpty (S)) Error ("Empty stack!") Else{FirstCell= s->Next; S->next = s->next->Next; Free(FirstCell); }}//make a stack emptyvoidmakeempty (Stack S) {if(s==NULL) Error ("must use Creatstake first") Else { while(!IsEmpty (S)) Pop (S); }}//Adding an element x to the stack svoidPush (ElementType X, Stack S) {Ptrtonode Tmpcell; Tmpcell=malloc(sizeof(structNode)); if(Tmpcell==null) FatalError ("Out of space!") Else{Tmpcell->element =X; Tmpcell->next = s->Next; S->next =Tmpcell; }}elementtype Top (Stack S) {if(! IsEmpty (S))returnS->next->Element; Error ("Empty Space"); return 0;/*Return value used to avoid warning*/}voidDisposestack (Stack S) {makeempty (s); Free(S);}//print Stack, the stack is gone.voidPrintstake (Stack S) { while(!IsEmpty (S)) {printf ("%d", Top (S)); Pop (S); }}
Teststack.c
#include"Stack.h"#include<stdio.h>#include<time.h>#include<stdlib.h>intMain () {Stack S; S=Creatstack (); printf ("randomly generated number of digits:"); Longamount; scanf_s ("%d", &amount); Srand ((unsigned) time (NULL)); for(Longi =0; I < amount; i++) Push (rand ()% +, S);//inserting elementsPrintstake (S); Disposestack (S);//Release Stack}
Basic operation of the stack