/*------------------------------------------------------------------*/ /* stackarrayao.c */ /* Author: Bob Dondero */ /* A Stack abstract object implementation as an array */ /*------------------------------------------------------------------*/ #include "stackao.h" #include #include enum {INITIAL_PHYS_LENGTH = 2}; enum {GROWTH_FACTOR = 2}; /*------------------------------------------------------------------*/ /* The state of the Stack */ /* The array in which items are stored. */ static double *pdArray; /* The index one beyond the top element. */ static int iTop; /* The number of elements in the array. */ static int iPhysLength; /* Is the Stack initialized? */ static int iInitialized = 0; /*------------------------------------------------------------------*/ void Stack_init(void) /* Initialize the Stack. It is a checked runtime error for the Stack to be initialized. */ { assert(! iInitialized); pdArray = (double*)calloc(INITIAL_PHYS_LENGTH, sizeof(double)); assert(pdArray != NULL); iTop = 0; iPhysLength = INITIAL_PHYS_LENGTH; iInitialized = 1; } /*------------------------------------------------------------------*/ void Stack_free(void) /* Free the resources consumed by the Stack. It is a checked runtime error for the Stack to be uninitialized. */ { assert(iInitialized); free(pdArray); iInitialized = 0; } /*------------------------------------------------------------------*/ static void Stack_grow(void) /* Double the physical length of the Stack. */ { assert(iInitialized); iPhysLength *= GROWTH_FACTOR; pdArray = (double*)realloc(pdArray, sizeof(double) * iPhysLength); assert(pdArray != NULL); } /*------------------------------------------------------------------*/ void Stack_push(double dItem) /* Push dItem onto the Stack. It is a checked runtime error for the Stack to be uninitialized. */ { assert(iInitialized); if (iTop == iPhysLength) Stack_grow(); pdArray[iTop] = dItem; iTop++; } /*------------------------------------------------------------------*/ double Stack_pop(void) /* Pop the Stack, and return the popped item. It is a checked runtime error for the Stack to be uninitialized or empty. */ { assert(iInitialized); assert(iTop > 0); iTop--; return pdArray[iTop]; } /*------------------------------------------------------------------*/ int Stack_isEmpty(void) /* Return 1 (TRUE) iff the Stack is empty. It is a checked runtime error for the Stack to be uninitialized. */ { assert(iInitialized); return iTop == 0; }