Leetcode - Evaluate Reverse Polish Notation
初看貌似有点复杂,可是搞懂了很easy,就一个简单的栈应用,每次遇到计算符号"+", "-", "*", "/"就将栈顶端两个数字出栈,计算后再将结果压栈就可以。
。
#include<iostream> #include<vector> #include<stack> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> stack; for (int i = 0; i < tokens.size(); i++) { if (tokens[i] == "*" || tokens[i] == "-" || tokens[i] == "+" || tokens[i] == "/") { int val2 = stack.top(); stack.pop(); int val1 = stack.top(); stack.pop(); int tmpVal; if (tokens[i] == "*") tmpVal = val1 * val2; else if (tokens[i] == "-") tmpVal = val1 - val2; else if (tokens[i] == "+") tmpVal = val1 + val2; else tmpVal = val1 / val2; stack.push(tmpVal); } else { int tmpVal = atoi(tokens[i].c_str()); stack.push(tmpVal); } } return stack.top(); } };