/*-------------------------------------------------------------------*/ /* stackarray.c (A Stack ADT Implementation as an Array) */ /*-------------------------------------------------------------------*/ #include "stack.h" #include #include #define INITIAL_PHYS_LENGTH 2 /*-------------------------------------------------------------------*/ struct Stack { double *pdArray; int iTop; 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 *= 2; 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; }