/* * the stack module */ #include #include #include /* * macros */ #define MAXSTACK 1024 /* maximum number of elements on stack */ /* * globals accessible only within this file * note they are declared as static */ static int stack[MAXSTACK]; /* the stack itself */ static int topstack = 0; /* index of above top element of stack */ /* * push a value onto the stack * exits on stack overflow */ int push(int val) { /* check for overflow */ if (topstack >= MAXSTACK){ fprintf(stderr, "Stack is full\n"); return(0); } /* push onto stack */ stack[topstack++] = val; return(1); } /* * pop a value from the stack * exits on stack underflow */ int pop(int *val) { /* check for an empty stack */ if (topstack <= 0){ fprintf(stderr, "Stack is empty\n"); return(0); } /* pop from stack */ *val = stack[--topstack]; return(1); } /* * print the top of the stack and the elements on the stack */ void prstack(void) { int i; /* used to walk the stack */ /* check for empty stack */ if (topstack == 0){ printf("stack is empty (top = %d\n", topstack); return; } /* print the top index */ printf("stack contains (top = %d)\n", topstack); /* now print the elements of the stack, top down */ for(i = topstack - 1; i >= 0; i--) printf("\t%3d: %10d\n", i, stack[i]); } #ifdef DEBUG /* convert string to integer; return 1 on success, 0 on error */ int stoi(char *s, int *n) { int sgn = 1; /* sign of input number */ /* initialize *n */ *n = 0; /* skip white space */ while (isspace(*s)) s++; /* is it negative? */ if (*s == '-'){ sgn = -1; s++; } /* go until there are no more digitss */ if (!isdigit(*s)) return(0); while(isdigit(*s)) *n = *n * 10 + (*s++ - '0'); *n *= sgn; /* return if you're at the end */ return(*s == '\0' || *s == '\n'); } /* * driver */ int main(void) { char buf[MAXSTACK]; /* input buffer */ char *b; /* pointer to buf */ int n; /* input number */ while(printf("+ for push, - for pop, p for print > "), fgets(buf, 1000, stdin) != NULL){ buf[strlen(buf)-1] = '\n'; for(b = buf; isspace(*b); b++) /* EMPTY */; switch(*b){ case '+': if(stoi(b+1, &n) == 0){ printf("%s: not an integer\n", b+1); continue; } if (push(n)) printf("\tpushed %d\n", n); continue; case '-': if (pop(&n)) printf("\tpopped %d\n", n); continue; case 'p': prstack(); continue; case '\0': continue; default: printf("TYPO: %s", buf); continue; } } putchar('\n'); return(0); } #endif