/* Array-based implementation of the ADT stack. */ #include "stack.h" #include /* for malloc, etc. & NULL */ typedef struct stacktype { int size, sp; /* Maximum size and current size */ void **items; /* Pointer to an array of void pointers */ } stacktype; stack stack_init(int size) { stack stk; stk = (stack)malloc(sizeof(stacktype)); /* space for the stack. */ if (stk == NULL) { /* no space? */ return NULL; } /* Now try for the array of void pointers */ stk->items = (void**)malloc(size*sizeof(void*)); if (stk->items == NULL) { /* no space for array? */ free(stk); /* Undo first allocation */ return NULL; /* report failure */ } /* Set up housekeeping fields of stack structure. */ stk->size = size; /* Maximum size */ stk->sp = 0; /* Stack starts out empty */ return stk; /* initialised stack */ } void stack_free(stack stk) { free(stk->items); /* Free array of pointers */ free(stk); /* Free stack */ } int stack_push(stack stk, void *item) { /* Detect overflow by checking the size limit. */ if (stk->sp >= stk->size) { return 0; /* fail */ } stk->items[stk->sp] = item; /* Record address in array */ stk->sp++; /* Count it. */ return 1; /* succeed */ } int stack_empty(stack stk) { return (stk->sp == 0); /* If true, stack is empty */ } void *stack_pop(stack stk) { void *item; if (stack_empty(stk)) { /* Check for item on stack */ return NULL; } item = stack_top(stk); /* Get top item. */ stk->sp--; /* Pop it from stack */ return item; } void *stack_top(stack stk) { if (stack_empty(stk)) { /* Check for item on stack */ return NULL; } return stk->items[stk->sp-1]; /* Return recorded address */ } int stack_count(stack stk) { return stk->sp; }