Infix expression evaluation
By integrating the functions of "infix to suffix" and "suffix evaluation" (not a simple sequential call), the infix expression can be evaluated directly. The new algorithm scans infix expression from left to right, but uses two stacks, one temporary operator and one temporary operand at the same time to evaluate. (support five operations + - * / ^)
Input example:
( 2 + 3 ) * 6 + 4 / 2
Output example:
32
#include <iostream> #include <string> #include <cstring> #include <cmath> using namespace std; stack< int > operant; stack< char > op; int calculate(int operand1, int operand2, char op) //operation { int result; switch (op) { case'+':result = operand1 + operand2; break; case'-':result = operand2 - operand1; break; case'*':result = operand1 * operand2; break; case'/':result = operand2 / operand1; break; case'^':result = pow(double(operand2), operand1); break; } return result; } void judgethepriority(char& c) //Determine symbol priority and operate { if (op.empty()) { op.push( c ); return; } char prev = op.top(); if (c == '+' || c == '-') { if (prev == '(') { op.push( c ); return; } int ope1 = operant.top(); operant.pop(); int ope2 = operant.top(); operant.pop(); int result = calculate(ope1, ope2, prev); op.pop(); operant.push(result); judgethepriority( c ); } else if (c == '*' || c == '/') { if (prev == '(' || prev == '+' || prev == '-') { op.push(c); return; } int ope1 = operant.top(); operant.pop(); int ope2 = operant.top(); operant.pop(); int result = calculate(ope1, ope2, prev); op.pop(); operant.push(result); judgethepriority( c ); } else if (c == '^') { if (prev == '^') { int ope1 = operant.top(); operant.pop(); int ope2 = operant.top(); operant.pop(); int result = calculate(ope1, ope2, prev); op.pop(); operant.push(result); judgethepriority( c ); } else { op.push( c ); return; } } else if (c == ')') { if (prev == '(') { op.pop(); return; } int ope1 = operant.top(); operant.pop(); int ope2 = operant.top(); operant.pop(); int result = calculate(ope1, ope2, prev); op.pop(); operant.push(result); judgethepriority( c ); } } int main() { char c; int number; while (cin >> c && c != EOF) { switch ( c ) { case' ':break; case'+':judgethepriority( c ); break; case'-':judgethepriority( c ); break; case'*':judgethepriority( c ); break; case'/':judgethepriority( c ); break; case'^':judgethepriority( c ); break; case'(':op.push( c ); break; case')':judgethepriority( c ); break; default: cin.putback( c ); cin >> number; operant.push(number); break; } } int goal; while (!op.empty()) { int n1 = operant.top(); operant.pop(); int n2 = operant.top(); operant.pop(); char op1 = op.top(); op.pop(); goal = calculate(n1, n2, op1); operant.push(goal); } cout << operant.top() << endl; return 0; }