Stack is a relatively basic data structure that restricts the deletion and insertion of operations in one place, and the main idea is last-in, first-out (LIFO).
Details can be seen through the code.
The Declarations section of the function is given below:
StackRecord.h
#ifndef Stackrecord_h#defineStackrecord_htypedefCharElementType;
structStackrecord;typedefstructStackrecord *Stack;intIsEmpty (Stack S);intisfull (Stack S); Stack Createstack (intmaxstacksize);voidDisposestack (Stack S);voidmakeempty (Stack S);voidPush (Stack S, ElementType X);voidPop (Stack S); ElementType Top (Stack S); ElementType popandtop (Stack S);#endif
In general, when we create a stack, we declare an array to store the elements, but this is an implied danger, and the average array size will have a definite value, and usually our program often has a potentially multiple stack. So we're applying for an array dynamically, although expensive malloc and free program time are expensive, but this fits our ADT idea!
The main routines of the stack are push () and pop () two routines:
STACKFUNCTION.C:
#include"StackRecord.h"#include<stdio.h>#include<stdlib.h>#defineemptystack-1/* default empty stack size */#defineMinstacksize 5structstackrecord{intcapacity; intTopofstack; ElementType*Array;};intIsEmpty (Stack S) {returnS->topofstack = =Emptystack;}intisfull (Stack S) {returnS->capacity = = S->topofstack +1;/* plus 1 because the size of the array starts at 0 */} Stack Createstack (intmaxstacksize) {Stack S; if(maxStackSize <minstacksize) printf ("Stack is too small!"); S= (Stack)malloc(sizeof(structStackrecord)); if(S = =NULL) printf ("malloc failure!"); Else{
/*alloc a arry size you wanted*/S->array = (elementtype*)malloc(sizeof(ElementType) *maxstacksize); if(S->array = =NULL) printf ("malloc failure!"); Else{S->capacity =maxstacksize; Makeempty (S); } } returnS;}voidMakeempty (Stack s) {s->topofstack =Emptystack;}voidDisposestack (Stack S) {if(S! = NULL) {//if S is NULL, that's free (S) is meaningless Free(s->Array); Free(S); }}voidPush (Stack S, ElementType X) {if(Isfull (S)) printf ("Stack is full!"); ElseS->array[++s->topofstack] =X;}voidPop (Stack S) {if(IsEmpty (S)) printf ("Stack is empty!"); ElseS->topofstack--;} ElementType Top (Stack S) {if(!IsEmpty (S))returnS->array[s->Topofstack]; printf ("Stack is empty!"); return 0;//return value used to avoid warning}elementtype popandtop (Stack S) {if(!IsEmpty (S))returns->array[s->topofstack--]; printf ("Stack is empty!"); return 0;}
Stack ——— Array Implementation