/*********************************************************** * * stack.c * * Implementation of the stack module. This file contains * the C code for the procedures that manipulate the stack * data structure. * ***********************************************************/ #include #include #include "stack.h" /* * Declare the data structure that is used for the stack * module. This data structure isn't visible outside of * this file. A simple array is used to store the data * in the stack. The stack structure also contains the * size of the stack, and the index of the current stack * top. */ struct stack_struct { int size; /* The size of the stack */ int top; /* Index of the top of the stack */ int* dataptr; /* The actual stack data */ }; /* * The stack_create procedure creates a new instance of * the stack data structure. The parameter to this procedure * is the maximum number of elements in the stack. The * value returned is a Stack value that can be passed to * the other functions in this module. */ Stack stack_create( int size ) { Stack result; result = (Stack) malloc( sizeof *result ); if ( result == NULL ) { printf( "out of memory in stack module\n" ); abort( ); } result->size = size; result->top = 0; result->dataptr = ( int * ) calloc( size, sizeof(int) ); if ( result->dataptr == NULL ) { printf( "out of memory in stack module\n" ); abort( ); } return( result ); } /* * The stack_destroy function returns the resources that have * been allocated to a stack instance. it is careful to set * all freed pointers to NULL so they can't be dereferenced */ Stack stack_destroy( Stack old ) { free( old->dataptr ); old->dataptr = NULL; free( old ); return( NULL ); } /* * The stack_push procedure add an item to the top of the stack. * If the stack is full, this procedure returns without adding * the item, keeps the stack in a valid state. */ void stack_push( Stack s, int item ) { if ( s->top == s->size ) return; s->dataptr[s->top] = item; s->top++; } /* * The stack_pop procedure removes the top item from the * stack and returns it. If the stack is already empty * it returns the value 0 without making any changes to * the stack. This preserves the valifity of the stack. */ int stack_pop( Stack s ) { if ( s->top == 0 ) return( 0 ); s->top--; return( s->dataptr[s->top] ); } /* * The stack_peek function returns the top item of the stack * without removing it from the stack. If the stack is already * empty this procedure returns 0. */ int stack_peek( Stack s ) { if ( s->top == 0 ) return( 0 ); return( s->dataptr[s->top-1] ); } /* * The stack_full function returns true if the stack is full, * otherwise it returns false. */ int stack_full( Stack s ) { if ( s->top == s->size ) return( 1 ); else return( 0 ); } /* * The stack_empty procedure returns true if the stack is * empty, otherwise it returns false. */ int stack_empty( Stack s ) { if ( s->top == 0 ) return( 1 ); else return( 0 ); }