/* Sandra N. Kardaras-Flick 03/27/05 STACKS A program that inputs a line of text and uses a stack to print the line reversed. */ #include #include #include #define STACK_SIZE 50 #define TRUE 1 #define FALSE 0 /* defines a new type, boolean, as a synonym for int */ typedef int boolean; /* function declarations */ void makeEmptyStack(void); /* function to make the stack empty */ boolean stackIsEmpty(void); /* function returns true if stack is empty */ boolean stackIsFull(void); /* function returns true if stack is full */ void push(int i); /* push the integer i onto the stack */ int pop(void); /* pop off the top integer from the stack */ void stackOverflow(void); /* error when you try to remove from empty stack */ void stackUnderflow(void); /* error whey you try to add to a full stack */ /* array of integers that stores the stack */ int contentsOfStack[STACK_SIZE]; /* pointer to the top of the stack */ int *top_ptr = &contentsOfStack[0]; int main() { int temp = 0; /* int to store each input */ makeEmptyStack(); /* set the stack empty */ printf("\n\n\n\n\t Enter your text:\t"); /* loop getting characters until end of line is reached */ while ((temp = getchar()) != '\n') { /* push the character in temp onto the stack */ push(temp); } printf("\tYour text reversed:\t"); while (!stackIsEmpty()) /* when stack is empty the loop will exit */ { /* pop an int off the stack and display */ printf("%c", pop()); } printf("\n\n\n\n"); return 0; } /* make the stack empty. */ void makeEmptyStack(void) { top_ptr = &contentsOfStack[0]; } /* check if the stack is empty.*/ boolean stackIsEmpty(void) { return top_ptr == &contentsOfStack[0]; } /* check if the stack is full. */ boolean stackIsFull(void) { return top_ptr == &contentsOfStack[STACK_SIZE]; } /* add int i to the end of the array. */ void push(int i) { if (stackIsFull()) /* can't add more to a full stack */ stackOverflow(); /* print overflow message and exit */ else *top_ptr++ = i; /* add i to the array, then increase top_ptr */ } /* take the top int off the stack and return it. */ int pop(void) { if (!stackIsEmpty()) /* can't pop from an empty stack */ return *--top_ptr; /* return the int at *top_ptr, and decrment top_ptr */ else stackUnderflow(); /* print error message and exit */ return 0; } /* print stack overflow error message and exit the program */ void stackOverflow(void) { printf("\nStack Overflow\n"); exit(EXIT_FAILURE); } /* print stack underflow error message and exit the program */ void stackUnderflow(void) { printf("\nStack Underflow\n"); exit(EXIT_FAILURE); }