/*array implementation declarations for stacks*/structStackrecord;typedefstructStackrecord *Stack;#defineMinsstacksize 5#defineEmptyTOS-1structstackrecord{intcapacity; intTopofstack; ElementType*Array;};/*creation of Stacks-array implementations*/Stackcreatestack (intmaxelements) {Stack S; if(Maxelements <maxstacksize) ERROR ("stack is too small"); S=malloc(sizeof(structStackrecord)); if(S = =NULL) FatalError ("Out of Space"); S->array =malloc(sizeof(ElementType) *maxelements); if(S->array = =NULL) FatalError ("Out of space"); S->capacity =maxelements; Makeempty (S); returnS;}/*array of events create empty stacks of routines*/voidMakeempty (Stack s) {s->topofstack =Emptytos;}/*Release Stack*/voidDisposestack (Stack S) {if(S! =NULL) { Free(s->Array); Free(S); }}/*a routine that monitors whether a stack is empty stack*/intIsEmpty (Stack S) {returnS->topofstack = =-1;}/*Judgment Stack Full*/intisfull (Stack S) {returnTopofstack = = Capacity-1;}/*example of a stack in the process*/voidPush (ElementType X, Stack S) {if(Isfull (S)) ERROR ("Stack is full"); ElseS->array[++s->topofstack] =X;}/*return to the top of the stack routine*/elementtypetop (Stack S) {if(IsEmpty (S)) {ERROR ("stack is empty"); return 0;//Avoid no } Else returns->array[s->topofstack];}/*Pop Operation*//*Topofstack is equivalent to a pointer to the top element of the stack*//*topofstack--just lets the pointer move down, but does not eliminate the original data, the next time push will be directly covered*//*and the S->array stack space is set, namely Maxelements*/voidPop (Stack S) {if(IsEmpty (S)) ERROR ("Empty Stack"); ElseS->topofstack--;} Elementtypepopandtop (Stack S) {if( !IsEmpty (S))returns->array[s->topofstack-- ];}
View Code
The core of this data structure is that the Stack s,s is a pointer to the structure with pointers inside the structure to point to the memory (array) address of malloc
A struct member consists of a topofstack (a pointer to the top element of the stack), a ElementType *array (which points to a contiguous memory of malloc, the equivalent of an array), a capacity (representing the capacity of the Stack = = maxelements)
malloc out of space is null fataerror ()
Pop and Top empty stacks or maxelements < minstacksize Error ()
But these two functions were not found, as if they were exception handling?
An array implementation of the stack ADT