逆波兰表达式,借助栈 来完成
C++ 代码
class Solution {
public:
stack<int> sta;
void cam(string s)
{
int a = sta.top();
sta.pop();
int b = sta.top();
sta.pop();
if(s == "+") sta.push(a+b);
else if(s == "-") sta.push(b-a);
else if(s == "*") sta.push(a*b);
else sta.push(b/a);
}
int evalRPN(vector<string>& tokens) {
int i = 0;
while(i < tokens.size())
{
if(tokens[i] == "+")cam("+");
else if(tokens[i] == "-")cam("-");
else if(tokens[i] == "*")cam("*");
else if(tokens[i] == "/")cam("/");
else
{
stringstream ss;
ss << tokens[i];
int z;
ss >> z;
sta.push(z);
}
i++;
//cout << sta.top()<<endl;
}
return sta.top();
}
};