/*-------------------------------------------------------------------*/ /* stackdynarray.c (Composition with DynArray) */ /*-------------------------------------------------------------------*/ #include "stack.h" #include "dynarray.h" #include #include /*-------------------------------------------------------------------*/ struct Stack { DynArray_T oDynArray; int iTop; }; /*-------------------------------------------------------------------*/ static int Stack_isValid(Stack_T oStack) /* Return 1 (TRUE) iff oStack is in a valid state. */ { if (oStack->oDynArray == NULL) return 0; if (oStack->iTop < 0) return 0; if (oStack->iTop > DynArray_getLength(oStack->oDynArray)) return 0; return 1; } /*-------------------------------------------------------------------*/ Stack_T Stack_new(void) /* Return a new Stack_T. */ { Stack_T oStack; oStack = (struct Stack*)malloc(sizeof(*oStack)); assert(oStack != NULL); oStack->oDynArray = DynArray_new(0); oStack->iTop = 0; return oStack; } /*-------------------------------------------------------------------*/ void Stack_free(Stack_T oStack) /* Free oStack. */ { if (oStack == NULL) return; DynArray_free(oStack->oDynArray); free(oStack); } /*-------------------------------------------------------------------*/ void Stack_push(Stack_T oStack, void *pvItem) /* Push pvItem onto oStack. It is a checked runtime error for oStack to be NULL. */ { assert(oStack != NULL); assert(Stack_isValid(oStack)); if (oStack->iTop < DynArray_getLength(oStack->oDynArray)) DynArray_put(oStack->oDynArray, oStack->iTop, pvItem); else DynArray_add(oStack->oDynArray, pvItem); ++(oStack->iTop); } /*-------------------------------------------------------------------*/ void *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(Stack_isValid(oStack)); assert(! Stack_isEmpty(oStack)); --(oStack->iTop); return DynArray_get(oStack->oDynArray, 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); assert(Stack_isValid(oStack)); return oStack->iTop == 0; }