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)), 6
Mainly the application of the stack:
Tockens[i] If it is the operand, press the stack directly. If it is an operator, the result of the two pop operation is calculated after the stack is pressed.
The element in the last stack is the result.
1 intEVALRPN (vector<string> &tokens)2 {3 intop_a, op_b;4stack<int>SK;5 for(inti =0; I < tokens.size (); i++)6 {7 stringstr =Tokens[i];8 if((str[0] =='+') || (str[0] =='-'&& str.size () = =1) || (str[0] =='*') || (str[0] =='/'))9 {TenOp_a =sk.top (); One Sk.pop (); AOp_b =sk.top (); - Sk.pop (); - Switch(str[0]) the { - Case '+': -Sk.push (Op_b +op_a); - Break; + Case '-': -Sk.push (Op_b-op_a); + Break; A Case '*': atSk.push (Op_b *op_a); - Break; - default: -Sk.push (Op_b/op_a); - } - } in Else - { to Sk.push (Atoi (Str.c_str ())); + } - } the returnsk.top (); *}
Leetcode 150. Evaluate Reverse Polish Notation