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

leetcode - Evaluate Reverse Polish Notation

2013-12-07 12:30 591 查看
class Solution {
public:
void parseNum(stack<int>& _stack, const string & token){
int number = atoi(token.c_str());
_stack.push(number);
}
void parseOperation(stack<int> & _stack, char token){
int num1 = _stack.top();
_stack.pop();
int num2 = _stack.top();
_stack.pop();
int rlt = 0;
switch(token){
case '+':
rlt= num2+num1;
break;
case '-':
rlt = num2-num1;
break;
case '*':
rlt= num2*num1;
break;
case '/':
rlt = num2/num1;
break;
}
_stack.push(rlt);
}
int evalRPN(vector<string> &tokens) {
stack<int> _stack;
vector<string>::iterator itr;;
for (itr=tokens.begin(); itr!=tokens.end(); itr++){
string token =  * itr;
if (token.length()==1){
char c = token.at(0);
if (c=='+' || c=='-' || c=='*' || c=='/')
parseOperation(_stack, c);
else parseNum(_stack, token);
}
else parseNum(_stack, token);
}
if (!_stack.empty())
return _stack.top();
return 0;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: