/*--------------------------------------------------------------------*/ /* stack.c (Version 2) */ /* Author: Bob Dondero */ /*--------------------------------------------------------------------*/ #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; }; /*--------------------------------------------------------------------*/ struct Stack *Stack_new(void) /* Return a new Stack. */ { struct Stack *psStack; psStack = (struct Stack *)malloc(sizeof(struct Stack)); assert(psStack != NULL); psStack->pdArray = (double*)calloc(INITIAL_PHYS_LENGTH, sizeof(double)); assert(psStack->pdArray != NULL); psStack->iTop = 0; psStack->iPhysLength = INITIAL_PHYS_LENGTH; return psStack; } /*--------------------------------------------------------------------*/ void Stack_free(struct Stack *psStack) /* Free psStack. Do nothing if psStack is NULL. */ { if (psStack == NULL) return; free(psStack->pdArray); free(psStack); } /*--------------------------------------------------------------------*/ static void Stack_grow(struct Stack *psStack) /* Double the physical length of *psStack. */ { assert(psStack != NULL); psStack->iPhysLength *= GROWTH_FACTOR; psStack->pdArray = (double*)realloc(psStack->pdArray, sizeof(double) * psStack->iPhysLength); assert(psStack->pdArray != NULL); } /*--------------------------------------------------------------------*/ void Stack_push(struct Stack *psStack, double dItem) /* Push dItem onto *psStack. It is a checked runtime error for psStack to be NULL. */ { assert(psStack != NULL); if (psStack->iTop == psStack->iPhysLength) Stack_grow(psStack); (psStack->pdArray)[psStack->iTop] = dItem; (psStack->iTop)++; } /*--------------------------------------------------------------------*/ double Stack_top(struct Stack *psStack) /* Return the top item of *psStack. It is a checked runtime error for psStack to be NULL or for *psStack to be empty. */ { assert(psStack != NULL); assert(psStack->iTop > 0); return (psStack->pdArray)[psStack->iTop - 1]; } /*--------------------------------------------------------------------*/ void Stack_pop(struct Stack *psStack) /* Pop *psStack, and discard the popped item. It is a checked runtime error for psStack to be NULL or for *psStack to be empty. */ { assert(psStack != NULL); assert(psStack->iTop > 0); (psStack->iTop)--; } /*--------------------------------------------------------------------*/ int Stack_isEmpty(struct Stack *psStack) /* Return 1 (TRUE) iff *psStack is empty. It is a checked runtime error for psStack to be NULL. */ { assert(psStack != NULL); return psStack->iTop == 0; }