/*---------------------------------------------------------------------- File : stack_l.c Contents: general stack management (singly connected list version) Author : Christian Borgelt History : 04.06.1998 file created ----------------------------------------------------------------------*/ #include #include #include "stack.h" /*---------------------------------------------------------------------- Type Definitions ----------------------------------------------------------------------*/ typedef struct _ste { /* --- a stack element --- */ struct _ste *succ; /* pointer to successor element */ void *obj; /* pointer to stored object */ } STE; /* (stack element) */ struct stack { /* --- a stack --- */ STE *top; /* pointer to top of stack */ }; /* (stack) */ /*---------------------------------------------------------------------- Functions ----------------------------------------------------------------------*/ STACK* stk_create (void) { /* --- create an empty stack */ STACK *stk; /* created stack */ stk = (STACK*)malloc(sizeof(STACK)); if (!stk) return NULL; /* allocate memory and */ stk->top = NULL; /* initialize field */ return stk; /* return the created stack */ } /* stk_create() */ /*--------------------------------------------------------------------*/ void stk_delete (STACK *stk) { /* --- delete a stack */ STE *ste, *tmp; /* to traverse the stack elements */ ste = stk->top; /* get the top stack element */ while (ste) { /* while there is another */ tmp = ste; /* stack element, note it, */ ste = ste->succ; /* remove it from the list, */ free(tmp); /* and delete it */ } /* (deallocate the memory) */ free(stk); /* delete the stack body */ } /* stk_delete() */ /*--------------------------------------------------------------------*/ int stk_empty (STACK *stk) { /* --- check whether stack is empty */ return (stk->top == NULL); /* check pointer to top element */ } /* stk_empty() */ /*--------------------------------------------------------------------*/ int stk_push (STACK *stk, void *obj) { /* --- push an object onto a stack */ STE *ste; /* new stack element */ ste = (STE*)malloc(sizeof(STE)); if (!ste) return -1; /* create a new stack element */ ste->obj = obj; /* enter pointer to object, */ ste->succ = stk->top; /* append current stack, */ stk->top = ste; /* and set new top element */ return 0; /* return `ok' */ } /* stk_push() */ /*--------------------------------------------------------------------*/ void* stk_pop (STACK *stk, int keep) { /* --- pop an object from a stack */ STE *ste; /* top stack element */ void *obj; /* object in top element */ if (stk->top == NULL) /* is the stack is empty, */ return NULL; /* abort the function */ ste = stk->top; /* get top stack element and */ obj = ste->obj; /* the object stored in it */ if (!keep) { /* if not to keep it on the stack, */ stk->top = ste->succ; /* remove top element from stack */ free(ste); /* and delete it */ } /* (deallocate the memory) */ return obj; /* return top object */ } /* stk_pop() */