/* * evaluate single digit operant postfix expression * modified from textbook example * HBF */ #include #include #define MAX 100 int evaluatePostfix(char exp[]); void push(int stk[], int *top, int val); void pop(int stk[], int *top); int peek(int stk[], int top); int main() { char postfixstr[100] = "934*8+4/-"; printf("%s = %d", postfixstr, evaluatePostfix(postfixstr)); return 0; } int evaluatePostfix(char exp[]) { int stk[MAX]; int top = -1; char *p = exp; int opr1, opr2, value; while ( *p ) { if (*p >= '0' && *p <= '9') { push(stk, &top, (int)(*p - '0')); } else { opr2 = peek(stk, top); pop(stk, &top); opr1 = peek(stk, top); pop(stk, &top); switch (*p) { case '+': value = opr1 + opr2; break; case '-': value = opr1 - opr2; break; case '/': value = opr1 / opr2; break; case '*': value = opr1 * opr2; break; case '%': value = opr1 % opr2; break; } push(stk, &top, value); } p++; } return (peek(stk, top)); } void push(int stk[], int *top, int val) { if (*top == MAX-1) { printf("\n STACK OVERFLOW"); } else { *top = *top + 1; stk[*top] = val; } } void pop(int stk[], int *top) { if (*top == -1) { printf("\n STACK UNDERFLOW"); } else { *top = *top - 1; } } int peek(int stk[], int top) { if (top == -1) { printf("\n STACK IS EMPTY"); return -1; } else return (stk[top]); } /* 934*8+4/- = 4 */