/* * stack_template.c - A type-independent template for a single stack. * Samuel A. Rebelsky * Version 1.0 of 11 February 2007 * * Note: To use this, you must define SPREFIX(thing), STYPE, and, optionaly, * INITIAL_STACK_SIZE */ #include #ifndef INITIAL_STACK_SIZE #define INITIAL_STACK_SIZE 16 #endif #define _S_STACK SPREFIX(stack) #define _S_TOP SPREFIX(top) #define _S_SIZE SPREFIX(size) /* Sam believes in stacks that can grow. */ STYPE *_S_STACK = NULL; /* The stack. */ int _S_TOP = 0; /* The top of the stack. */ int _S_SIZE = 0; /* The current size of the stack. */ void SPREFIX(push)(STYPE val) { /* If no stack exists, create one. */ if (NULL == _S_STACK) { _S_SIZE = INITIAL_STACK_SIZE; _S_STACK = (STYPE *) malloc(_S_SIZE * sizeof(STYPE)); _S_TOP = 0; } /* If the stack is too small, expand it. */ if (_S_SIZE == _S_TOP) { STYPE *newstack = (STYPE *) malloc(2*_S_SIZE*sizeof(STYPE)); /* WARNING! Did not check whether the result is null. */ int i; for (i = 0; i < _S_SIZE; i++) { newstack[i] = _S_STACK[i]; } free(_S_STACK); _S_STACK = newstack; _S_SIZE = 2*_S_SIZE; } /* We're FINALLY ready to push the value. */ _S_STACK[_S_TOP++] = val; } /* push(int) */ STYPE SPREFIX(pop)() { return _S_STACK[--_S_TOP]; } /* pop() */ STYPE SPREFIX(empty)() { return !_S_TOP; } /* empty() */ #undef _S_STACK #undef _S_TOP #undef _S_SIZE