Evaluate Reverse Polish Notation
2014-02-19 15:52
288 查看
#include <iostream> #include <vector> #include <stack> #include <string> using namespace std; class Solution { public: int evalRPN(vector<string> &tokens) { stack<int> expvalue; vector<string>::iterator iter; int last1, last2; for (iter = tokens.begin(); iter != tokens.end(); iter++) { if ( (*iter) == "+" ) { last1 = expvalue.top(); expvalue.pop(); last2 = expvalue.top(); expvalue.pop(); expvalue.push( last2 + last1); } else if( (*iter) == "-" ) { last1 = expvalue.top(); expvalue.pop(); last2 = expvalue.top(); expvalue.pop(); expvalue.push( last2 - last1); } else if( (*iter) == "*" ) { last1 = expvalue.top(); expvalue.pop(); last2 = expvalue.top(); expvalue.pop(); expvalue.push( last2 * last1); } else if( (*iter) == "/" ) { last1 = expvalue.top(); expvalue.pop(); last2 = expvalue.top(); expvalue.pop(); expvalue.push( last2 / last1); } else { expvalue.push(atoi((*iter).c_str() )); } } return expvalue.top(); } }; int main() { string str[]={"2", "1", "+", "3", "*"}; vector<string> tokens(str,str+sizeof(str)/sizeof(str[0])); Solution sln; cout << sln.evalRPN(tokens) << endl; return 0; }
相关文章推荐
- LeetCode | Evaluate Reverse Polish Notation
- LeetCode - Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 150. Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation
- 4.1.4—栈—Evaluate Reverse Polish Notation
- 【LeetCode】Evaluate Reverse Polish Notation
- LeetCode Evaluate Reverse Polish Notation
- Leetcode-Evaluate Reverse Polish Notation-java
- 【Leetcode-medium-150】Evaluate Reverse Polish Notation
- [LeetCode] Evaluate Reverse Polish Notation [2]
- LeetCode第一题:Evaluate Reverse Polish Notation
- 80_leetcode_Evaluate Reverse Polish Notation
- Evaluate Reverse Polish Notation ---Java
- LeetCode: Evaluate Reverse Polish Notation [150]
- LeetCode Evaluate Reverse Polish Notation
- [leetcode] Evaluate Reverse Polish Notation
- LeetCode | Evaluate Reverse Polish Notation(逆波兰式求值)
- Evaluate_Reverse_Polish_Notation 表达式求值