/*------------------------------------------------------------------*/ /* stackao.c (A Stack Abstract Object) */ /*------------------------------------------------------------------*/ #include #include #include "stackao.h" struct StackNode { const void *pvItem; struct StackNode *psNextNode; }; /*------------------------------------------------------------------*/ /* The state of the Stack */ static int iInitialized = 0; static struct StackNode *psFirstNode; /*------------------------------------------------------------------*/ void Stack_init(void) /* Initialize the Stack. It is a checked runtime error for the Stack to be initialized. */ { assert(! iInitialized); psFirstNode = NULL; iInitialized = 1; } /*------------------------------------------------------------------*/ void Stack_free(void) /* Free the resources consumed by the Stack. It is a checked runtime error for the Stack to be uninitialized. */ { struct StackNode *psCurrentNode; struct StackNode *psNextNode; assert(iInitialized); for (psCurrentNode = psFirstNode; psCurrentNode != NULL; psCurrentNode = psNextNode) { psNextNode = psCurrentNode->psNextNode; free(psCurrentNode); } iInitialized = 0; } /*------------------------------------------------------------------*/ void Stack_push(const void *pvItem) /* Push pvItem onto the Stack. It is a checked runtime error for the Stack to be uninitialized. */ { struct StackNode *psNewNode; assert(iInitialized); psNewNode = (struct StackNode*)malloc(sizeof(*psNewNode)); assert(psNewNode != NULL); psNewNode->pvItem = pvItem; psNewNode->psNextNode = psFirstNode; psFirstNode = psNewNode; } /*------------------------------------------------------------------*/ void *Stack_pop(void) /* Pop the Stack, and return the popped item. It is a checked runtime error for the Stack to be uninitialized or empty. */ { const void *pvItem; struct StackNode *psNextNode; assert(iInitialized); assert(! Stack_isEmpty()); pvItem = psFirstNode->pvItem; psNextNode = psFirstNode->psNextNode; free(psFirstNode); psFirstNode = psNextNode; return (void*)pvItem; } /*------------------------------------------------------------------*/ int Stack_isEmpty(void) /* Return 1 (TRUE) iff the Stack is empty. It is a checked runtime error for the Stack to be uninitialized. */ { assert(iInitialized); return psFirstNode == NULL; }