/*------------------------------------------------------------------*/ /* stacklist.c (A Stack ADT Implementation as a Linked List) */ /*------------------------------------------------------------------*/ #include #include #include "stack.h" /*------------------------------------------------------------------*/ /* Each item is stored in a StackNode. StackNodes are linked to form a list. */ struct StackNode { double dItem; /* The item. */ struct StackNode *psNextNode; /* The address of the next StackNode. */ }; /*------------------------------------------------------------------*/ /* A Stack is a "dummy" node that points to the first StackNode. */ struct Stack { struct StackNode *psFirstNode; /* The address of the first StackNode. */ }; /*------------------------------------------------------------------*/ Stack_T Stack_new(void) /* Return a new Stack_T. */ { Stack_T oStack; oStack = (Stack_T)malloc(sizeof(struct Stack)); assert(oStack != NULL); oStack->psFirstNode = NULL; return oStack; } /*------------------------------------------------------------------*/ void Stack_free(Stack_T oStack) /* Free oStack. */ { struct StackNode *psCurrentNode; struct StackNode *psNextNode; if (oStack == NULL) return; for (psCurrentNode = oStack->psFirstNode; psCurrentNode != NULL; psCurrentNode = psNextNode) { psNextNode = psCurrentNode->psNextNode; free(psCurrentNode); } free(oStack); } /*------------------------------------------------------------------*/ void Stack_push(Stack_T oStack, double dItem) /* Push dItem onto oStack. It is a checked runtime error for oStack to be NULL. */ { struct StackNode *psNewNode; assert(oStack != NULL); psNewNode = (struct StackNode*)malloc(sizeof(struct StackNode)); assert(psNewNode != NULL); psNewNode->dItem = dItem; psNewNode->psNextNode = oStack->psFirstNode; oStack->psFirstNode = psNewNode; } /*------------------------------------------------------------------*/ 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. */ { double dItem; struct StackNode *psNextNode; assert(oStack != NULL); assert(oStack->psFirstNode != NULL); dItem = oStack->psFirstNode->dItem; psNextNode = oStack->psFirstNode->psNextNode; free(oStack->psFirstNode); oStack->psFirstNode = psNextNode; return dItem; } /*------------------------------------------------------------------*/ 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->psFirstNode == NULL; }