Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is + , - , * , / . Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Analysis: Reverse Polish notation can be obtained by post traversal compute tree, we can evaluate its value through the stack, the code is as follows:
1 classSolution {2 Public:3 intEVALRPN (vector<string> &tokens) {4 intresult =0;5stack<int>S;6 7 for(inti =0; I < tokens.size (); i++){8 if(Is_operator (Tokens[i])) {9 intRV =s.top ();Ten S.pop (); One intLV =s.top (); A S.pop (); - if(Tokens[i] = ="+") -S.push (LV +RV); the Else if(Tokens[i] = ="-") -S.push (LV-RV); - Else if(Tokens[i] = ="*") -S.push (LV *RV); + Else if(Tokens[i] = ="/") -S.push (LV/RV); +}Else{ A S.push (Atoi (Tokens[i].c_str ())); at } - } - returns.top (); - } - - BOOLIs_operator (strings) { in returns = ="+"|| s = ="-"|| s = ="*"|| s = ="/"; - } to};
Leetcode:evaluate Reverse Polish Notation