/*------------------------------------------------------------------*/ /* stackarray.c */ /* Author: Bob Dondero */ /* A Stack ADT implementation as an array */ /*------------------------------------------------------------------*/ #include "stack.h" #include #include enum {INITIAL_PHYS_LENGTH = 2}; enum {GROWTH_FACTOR = 2}; /*------------------------------------------------------------------*/ /* A Stack consists of an array of items, and related data. */ struct Stack { /* The array in which items are stored. */ double *pdArray; /* The index one beyond the top element. */ int iTop; /* The number of elements in the array. */ int iPhysLength; }; /*------------------------------------------------------------------*/ Stack_T Stack_new(void) /* Return a new Stack_T. */ { Stack_T oStack; oStack = (Stack_T)malloc(sizeof(struct Stack)); assert(oStack != NULL); oStack->pdArray = (double*)calloc(INITIAL_PHYS_LENGTH, sizeof(double)); assert(oStack->pdArray != NULL); oStack->iTop = 0; oStack->iPhysLength = INITIAL_PHYS_LENGTH; return oStack; } /*------------------------------------------------------------------*/ void Stack_free(Stack_T oStack) /* Free oStack. */ { if (oStack == NULL) return; free(oStack->pdArray); free(oStack); } /*------------------------------------------------------------------*/ static void Stack_grow(Stack_T oStack) /* Double the physical length of oStack. */ { assert(oStack != NULL); oStack->iPhysLength *= GROWTH_FACTOR; oStack->pdArray = (double*)realloc(oStack->pdArray, sizeof(double) * oStack->iPhysLength); assert(oStack->pdArray != NULL); } /*------------------------------------------------------------------*/ void Stack_push(Stack_T oStack, double dItem) /* Push dItem onto oStack. It is a checked runtime error for oStack to be NULL. */ { assert(oStack != NULL); if (oStack->iTop == oStack->iPhysLength) Stack_grow(oStack); (oStack->pdArray)[oStack->iTop] = dItem; (oStack->iTop)++; } /*------------------------------------------------------------------*/ double Stack_pop(Stack_T oStack) /* Pop oStack, and return the popped item. It is a checked runtime error for oStack to be NULL or empty. */ { assert(oStack != NULL); assert(oStack->iTop > 0); (oStack->iTop)--; return (oStack->pdArray)[oStack->iTop]; } /*------------------------------------------------------------------*/ int Stack_isEmpty(Stack_T oStack) /* Return 1 (TRUE) iff oStack is empty. It is a checked runtime error for oStack to be NULL. */ { assert(oStack != NULL); return oStack->iTop == 0; }