Inverse Polish formula and expression solving
/************** Inverse Polish-suffix notation preprocessing-> infix to postfix algorithm: while (the expression is not empty) if (when an operand is encountered) directly outputs else if (when an operator op is encountered) op is (directly in the stack s op is) s. push the output until (op is an arithmetic operation, if (s is empty | s. top is (| op with a higher priority than s. top) op into the stack else s. push output if (! S. empty) s. push output computing algorithm: if (encountering operands) into Stack s else (encountering operator) s. push two elements for calculation and result into Stack *********************/# include
# Include
Using namespace std; typedef struct tagCalc {bool is_op; union {char op; int value ;};} Calc; int main () {stack
S; Calc calc; int ch; while (1) {while (ch = getchar () & ch! = '\ N') {if (NULL = strchr ("+-*/", ch) // operand {if (strchr ("()", ch) = NULL) printf ("% c", ch); if ('= ch) {calc. is_op = 1; calc. op = ch; s. push (calc);} else if (')' = ch) {while (! S. empty () {calc = s. top (); s. pop (); if ('= calc. op) break; printf ("% c", calc. op) ;}} else {if (s. empty () | s. top (). op = '(' | (NULL! = Strchr ("*/", ch) & NULL! = Strchr ("+-", s. top (). op) {calc. is_op = true; calc. op = ch; s. push (calc);} else {calc = s. top (); s. pop (); printf ("% c", calc. op) ;}}while (! S. empty () {calc = s. top (); s. pop (); printf ("% c", calc. op) ;}printf ("\ n ");}}