The algorithm for evaluating any postfix expression is fairly straightforward:
While there are input tokens left
-
- Read the next token from input.
- If the token is a value
- Push it onto the stack.
- Otherwise, the token is an operator (operator here includes both operators and functions).
- It is known that the operator takes n arguments.
- If there are fewer than n values on the stack
- (Error) The user has not input sufficient values in the expression.
- Else, Pop the top n values from the stack.
- Evaluate the operator, with the values as arguments.
- Push the returned results, if any, back onto the stack.
- If there is only one value in the stack
- That value is the result of the calculation.
- Otherwise, there are more values in the stack
- (Error) The user input has too many values.
1 class Solution { 2 public: 3 int evalRPN(vector&tokens) { 4 if (tokens.empty()) return 0; 5 6 stack st; 7 8 for (int i = 0; i < tokens.size(); ++i) { 9 if (tokens[i] == "+" || tokens[i] == "-" || tokens[i] == "*" || tokens[i] == "/") {10 if (st.empty()) return 0;11 int n1 = st.top();12 st.pop();13 if (st.empty()) return 0;14 int n2 = st.top();15 st.pop();16 if (tokens[i] == "+") st.push(n1 + n2);17 else if (tokens[i] == "-") st.push(n2 - n1);18 else if (tokens[i] == "*") st.push(n2 * n1);19 else if (n1 == 0) return 0;20 else st.push(n2 / n1);21 } else {22 st.push(atoi(tokens[i].c_str()));23 }24 }25 26 return st.top();27 }28 };