Header file
1typedefintElementType;2 3 #ifndef _stack_ar_4 #define_stack_ar_5 6 structStackrecord;7typedefstructStackrecord *Stack;8 9 intIsEmpty (Stack S);Ten intisfull (Stack S); OneStack Createstack (intmaxelements); A voidDisposestack (Stack S); - voidmakeempty (Stack S); - voidPush (ElementType X, Stack S); the ElementType Top (Stack S); - voidPop (Stack S); - ElementType Topandpop (Stack S); - + #endif
source file
1#include"Stackar.h"2#include <malloc.h>3#include"fatal.h"4#include <stdlib.h>5 6 #defineEmptytos (-1)7 #defineMinstacksize (5)8 9 structStackrecordTen { One intcapacity; A intTopofstack; -ElementType *Array; - }; the - intIsEmpty (Stack S) - { - returnS->topofstack = =Emptytos; + } - + intisfull (Stack S) A { at returnS->topofstack = = s->capacity-1; - } - -Stack Createstack (intmaxelements) - { - Stack S; in - if(Maxelements <minstacksize) toError ("Stack size is to small!"); + -S = (Stack)malloc(sizeof(structStackrecord)); the if(S = =NULL) *FatalError ("Out of space!"); $ Panax NotoginsengS->array = (elementtype*)malloc(sizeof(ElementType) *maxelements); - if(S->array = =NULL) theFatalError ("Out of space!"); +S->capacity =maxelements; A Makeempty (S); the + returnS; - } $ $ voidDisposestack (Stack S) - { - if(S! =NULL) the { - Free(s->Array);Wuyi Free(S); the } - } Wu - voidmakeempty (Stack S) About { $ if(S = =NULL) -Error ("Create Stack first!"); - Else -S->topofstack =Emptytos; A } + the voidPush (ElementType X, Stack S) - { $ if(Isfull (S)) theError ("Full srack!"); the Else theS->array[++s->topofstack] =X; the } - in ElementType Top (Stack S) the { the if(IsEmpty (S)) About { theError ("Empty srack!"); the return 0;/*return value used to avoid warning*/ the } + Else - returnS->array[s->Topofstack]; the }Bayi the voidPop (Stack S) the { - if(IsEmpty (S)) -Error ("Empty srack!"); the Else the--s->Topofstack; the } the - ElementType Topandpop (Stack S) the { the if(IsEmpty (S)) the {94Error ("Empty srack!"); the return 0;/*return value used to avoid warning*/ the } the Else98 returns->array[s->topofstack--]; About}
Test file
1#include <stdio.h>2#include"Stackar.h"3 4 Main ()5 {6 Stack S;7 inti;8 9S = Createstack ( A );Ten for(i =0; I <Ten; i++ ) One Push (i, S); A - while( !IsEmpty (S)) - { theprintf"%d\n", Top (S)); - Pop (S); - } - + Disposestack (S); - return 0; +}
[Data structure and algorithm]: array implementation of stacks