您的位置:首页 > 编程语言 > Lua

LeetCode problem 2: Evaluate Reverse Polish Notation

2014-03-30 22:09 344 查看
思路:碰到符号从数据栈中取两个数计算,再将计算结果压入数据栈中,最后得到的数据栈栈顶就是所求的结果。

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: