LeetCode problem 2: Evaluate Reverse Polish Notation

来源:互联网 发布:中国社交网络使用排名 编辑:程序博客网 时间:2024/06/05 17:40

思路:碰到符号从数据栈中取两个数计算,再将计算结果压入数据栈中,最后得到的数据栈栈顶就是所求的结果。

class Solution {public:   int evalRPN(vector<string> &tokens) {   stack<int> num;   int a,b,c;   for(vector<string>::iterator it = tokens.begin();it != tokens.end();it++){   if("+" == *it || "*" == *it || "-" == *it || "/" == *it){   a = num.top();   num.pop();   b = num.top();   num.pop();      char str = (*it).at(0);   switch(str){   case '+': c = a + b; break;   case '-': c = b - a; break;   case '*': c = a*b;   break;   case '/': c = b/a;   break;   }   num.push(c);   }   else{   const char *p;   int n;   p = (*it).c_str();   n = atoi(p);   num.push(n);   }   }   a = num.top();   return a;   }};

欢迎指出bug。

0 0
原创粉丝点击