/***************************************************** Author : Yan Huang Date : 02.18.07 Synopsis: convert a prefix expression to postfix expression **************************************************************/ #include #include /************************************************ Get the next token, symbol is the character representation, which is returned, the token is represented by its enumerated value, which is returned in the function name ***************************************************/ enum Precedence= {lparen,rparen,plus,minus,divide,times,mod,eos,operand}; Precedence get_token() { char symbol; cin >> symbol; switch (symbol) { case '(' : return lparen; case ')' : return rparen; case '+': return plus; case '-' : return minus; case '/' : return divide; case '*' : return times; case '%' : return mod; case '\n' : return eos; default : cin.unget(); return operand; /* no error checking, default is operand */ } } /************************************************************ Evaluate a postfix expression, expr, maintained as a global variable, '\0' is the the end of the expression. The stack and top of the stack are global variables. get_token is used to return the token type and the character symbol. Operands are assumed to be single character digits *****************************************************************/ int main(void) { Precedence token; char symbol; int op1, op2, op; int n = 0; /* counter for the expression string */ Stack expression; token = get_token(&symbol, &n); while (token != eos) { if (token == operand) cin >> op; /* no error check */ expression.push(op); /* stack insert */ else { /* remove two operands, perform operation, and return result to the stack */ op2 = pop(&top); /* stack delete */ op1 = pop(&top); switch(token) { case plus: push(&top, op1+op2); break; case minus: push(&top, op1-op2); break; case times: push(&top, op1*op2); break; case divide: push(&top, op1/op2); break; case mod: push(&top, op1%op2); } } token = get_token (&symbol, &n); } return pop(&top); /* return result */ }