Saturday, November 8, 2014

Evaluate Reverse Polish Notation

use stack   
int evalRPN(vector<string> &tokens) {
        stack<int> s;
        for (int i = 0; i < tokens.size(); ++i) {
            if (tokens[i] != "+" && tokens[i] != "-" && tokens[i] != "*" && tokens[i] != "/")
                s.push(stoi(tokens[i]));
            else {
                int op2 = s.top();s.pop();
                int op1 = s.top();s.pop();
                int result = 0;
                if(tokens[i] == "+")
                    result = op1 + op2;
                else if(tokens[i] == "-")
                    result = op1 - op2;
                else if(tokens[i] == "*")
                    result = op1 * op2;
                else if(tokens[i] == "/")
                    result = op1 / op2;
                s.push(result);
            }
        }
        return s.top();
 }

No comments:

Post a Comment