代码改变世界

leetcode - Evaluate Reverse Polish Notation

2013-12-07 12:30  张汉生  阅读(153)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     void parseNum(stack<int>& _stack, const string & token){
 4     int number = atoi(token.c_str());
 5     _stack.push(number);
 6     }
 7     void parseOperation(stack<int> & _stack, char token){
 8     int num1 = _stack.top();
 9     _stack.pop();
10     int num2 = _stack.top();
11     _stack.pop();
12     int rlt = 0;
13     switch(token){
14     case '+':
15         rlt= num2+num1;
16         break;
17     case '-':
18         rlt = num2-num1;
19         break;
20     case '*':
21         rlt= num2*num1;
22         break;
23     case '/':
24         rlt = num2/num1;
25         break;
26     }
27     _stack.push(rlt);
28     }
29     int evalRPN(vector<string> &tokens) {
30     stack<int> _stack;
31     vector<string>::iterator itr;;
32     for (itr=tokens.begin(); itr!=tokens.end(); itr++){
33         string token =  * itr;
34         if (token.length()==1){
35         char c = token.at(0);
36         if (c=='+' || c=='-' || c=='*' || c=='/')
37             parseOperation(_stack, c);
38         else parseNum(_stack, token);
39         }
40         else parseNum(_stack, token);
41     }
42     if (!_stack.empty())
43         return _stack.top();
44     return 0;
45     }
46 };