Iterate the expression from left to right and keep on storing the operands into a stack. Once an operator is received, pop the two topmost elements and evaluate them and push the result in the stack again.
Sr no. | Postfix | Stack |
---|
// Postfix Evaluator // Name - Tirthraj Mahajan #include <iostream> #include <stack> #include <string> #include <cmath> #include <stdexcept> using namespace std; bool isOperand(char ch){ if (ch!='+'&&ch!='-'&&ch!='*'&&ch!='/'&&ch!='('&&ch!=')'&&ch!='^') { return true; } else{ return false; } } int operation(char ch, int a, int b) { switch(ch) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': if (b != 0) { return a / b; } else { throw invalid_argument("Division by zero"); } case '^': return int(pow(a, b)); default: throw invalid_argument("Unsupported operation"); } } int evaluation(string postfix){ // A Temporary variable to store the string to interger conversion int num; // Stack to handle the postfix expression stack<int> st; for(int i=0; i<postfix.length(); i++){ // if the current element in postfix expression is an operand, then "try" to convert that 'char' into 'int' using try catch block and stoi function given in std::string class in C++11 or more // You can also use stringstream from sstream library to convert string into integer if(isOperand(postfix[i])){ try{ num = stoi(string(1, postfix[i])); //convert char to string before stoi function st.push(num); } catch(const invalid_argument &e){ cout<<"Invalid Argument Error! Please enter numbers"<<endl; return -1; } } else{ int a, b, c; b = st.top(); st.pop(); a = st.top(); st.pop(); c = operation(postfix[i],a,b); st.push(c); } } return st.top(); } int main() { string postfix = "15+"; cout<<"Evaluation: "<< evaluation(postfix)<<endl; return 0; }
// Postfix Evaluator // Name: Tirthraj Mahajan function isOperand(val){ if(val=='('||val==')'||val=='+'||val=='-'||val=='/'||val=='*'||val=='^'||val=='–'){ return false; } return true; } function operation(a, b, operation){ switch(operation){ case '+': return a+b; break; case '-': return a-b; break; case '–': return a-b; break; case '*': return a*b; break; case '/': return a/b; break; case '^': return a**b; break; default: console.log("Invalid Operation ", operation); return 0; } } let numStack = []; function evaluate(expression){ let expressionArr = expression.split(" "); console.log("Expression Array: ",expressionArr); let stack = []; for(let i=0; i<expressionArr.length; i++){ if(isOperand(expressionArr[i])){ stack.push(expressionArr[i]); numStack.push(Number(expressionArr[i])); }else{ let b = stack.pop(); let a = stack.pop(); stack.push(`(${a} ${expressionArr[i]} ${b})`); let num2 = numStack.pop(); let num1 = numStack.pop(); numStack.push(operation(num1,num2,expressionArr[i])); } } return stack[stack.length-1]; } let postfix = "10 5 +"; console.log(evaluate(postfix)); if(!isNaN(numStack[numStack.length-1])){ console.log("Evaluation Result : ",numStack[numStack.length-1]); }