/*-------------------------------------------------------------------*/ /* stackarrayao.c (A Stack Abstract Object Implementation as an Array)*/ /*-------------------------------------------------------------------*/ #include "stackao.h" #include #include #define INITIAL_PHYS_LENGTH 2 /*-------------------------------------------------------------------*/ /* The state of the Stack */ static double *pdArray; static int iTop; static int iPhysLength; 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 *= 2; 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; }