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

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