#include struct stack { int data; struct stack *next; }; typedef struct stack s_list; typedef s_list *link; link operator = NULL; link operand = NULL; void push(char ff,int value) { link node; node = ( link ) malloc(sizeof(s_list)); node->data = value; if (ff == 1) { node->next = operator; operator = node; } else { node->next=operand; operand=node; } } int pop(char ff) { link top; int value; if (ff == 1) { if (operator != NULL ) { top = operator; operator = operator->next; value = top->data; free(top); } else value = -1; } else { if (operand != NULL ) { top = operand; operand = operand->next; value = top->data; free(top); } else value = -1; } return value; } int empty(link stack) { if ( stack == NULL ) return 1; else return 0; } int isoperator(char op) { switch (op) { case '(': case ')': case '+': case '-': case '*': case '^': case '/': return 1; default: return 0; } } int prior(int op) { switch ( op ) { case '^': return 3; case '*': case '/': return 2; case '+': case '-': return 1; default: return 0; } } int get_value(int op,int operand1,int operand2) { switch ( (char) op ) { case '*': return ( operand1 * operand2 ); case '/': return ( operand1 / operand2 ); case '+': return ( operand1 + operand2 ); case '-': return ( operand1 - operand2 ); } } void main() { char exp[100]; int op = 0, s1=0, operand1 = 0, operand2 = 0, result = 0, pos = 0,k; printf("input expression ==> "); gets(exp); while ( exp[pos] != '\0' && exp[pos] != '\n' ) { if (isoperator(exp[pos])) { /* '+ - * /' */ if (exp[pos] == '(') push(1,'('); else if (exp[pos] == ')') { push(2,s1); s1=0; while (!empty(operator) && (op=pop(1))!='(') { operand2=pop(2); operand1=pop(2); push(2, (k=get_value(op,operand1,operand2))); printf("%d%c%d=%d\n",operand1,op,operand2,k); } } else { if (s1 != 0) { push(2, s1); s1=0; } if ( !empty(operator) ) while (prior(exp[pos]) <= prior(operator->data) && !empty(operator)) { op=pop(1); operand2=pop(2); operand1=pop(2); push(2, (k=get_value(op,operand1,operand2))); printf("%d%c%d=%d\n",operand1,op,operand2,k); } push(1,exp[pos]); } } else s1=s1*10+exp[pos]-48; pos++; } if (s1 != 0) push(2,s1); while ( !empty(operator) ) { op = pop(1); operand2 = pop(2); operand1 = pop(2); push(2,(k=get_value(op,operand1,operand2))); } result = pop(2); printf("%s=%d\n",exp,result); }