/*--------------------------------------------------------------------*/ /* stackao.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 */ static double *pdArray; /* The array in which items are stored. */ static int iTop; /* The index one beyond the top element. */ static int iPhysLength; /* The number of elements in the array. */ static int iInitialized = 0; /* Is the Stack initialized? */ /*--------------------------------------------------------------------*/ int Stack_init(void) /* Initialize the Stack object. Return 1 (TRUE) if successful, or 0 (FALSE) if insufficient memory is available. */ { assert(! iInitialized); pdArray = (double*)calloc(INITIAL_PHYS_LENGTH, sizeof(double)); if (pdArray == NULL) return 0; iTop = 0; iPhysLength = INITIAL_PHYS_LENGTH; iInitialized = 1; return 1; } /*--------------------------------------------------------------------*/ void Stack_free(void) /* Free the resources consumed by the Stack object, and uninitialize it. */ { assert(iInitialized); free(pdArray); iInitialized = 0; } /*--------------------------------------------------------------------*/ static int Stack_grow(void) /* Increase the physical length of the Stack object. Return 1 (TRUE) if successful, or 0 (FALSE) if insufficient memory is available. */ { int iNewPhysLength; double *pdNewArray; assert(iInitialized); iNewPhysLength = iPhysLength * GROWTH_FACTOR; pdNewArray = (double*) realloc(pdArray, sizeof(double) * iNewPhysLength); if (pdNewArray == NULL) return 0; iPhysLength = iNewPhysLength; pdArray = pdNewArray; return 1; } /*--------------------------------------------------------------------*/ int Stack_push(double dItem) /* Push dItem onto the Stack object. Return 1 (TRUE) if successful, or 0 (FALSE) is insufficient memory is available. */ { assert(iInitialized); if (iTop == iPhysLength) if (! Stack_grow()) return 0; pdArray[iTop] = dItem; iTop++; return 1; } /*--------------------------------------------------------------------*/ double Stack_top(void) /* Return the top item of the Stack object. */ { assert(iInitialized); assert(iTop > 0); return pdArray[iTop - 1]; } /*--------------------------------------------------------------------*/ void Stack_pop(void) /* Pop and discard the top item of the Stack object. */ { assert(iInitialized); assert(iTop > 0); iTop--; } /*--------------------------------------------------------------------*/ int Stack_isEmpty(void) /* Return 1 (TRUE) if the Stack object is empty, or 0 (FALSE) otherwise. */ { assert(iInitialized); return iTop == 0; }