逆波兰表达式又叫做后缀表达式:如下
a+b --> a,b,+
a+(b-c) --> a,b,c-,+
/*
问题描述:逆波兰表达式
作者:syt
日期:2018-03-07
*/
#include <iostream>
#include <string>
#include <stack>
using namespace std;
class PolishExp
{
public:
PolishExp(string s = "")
{
str = s;
}
bool isOperator(char s)
{
if (s == '+' || s == '-' || s == '*' || s == '/')
return true;
else
return false;
}
int calculation()
{
for (int i = 0; i < str.length(); i++)
{
if (isOperator(str[i]))
{
int x = mystack.top();
mystack.pop();
int y = mystack.top();
mystack.pop();
mystack.push(doCalculation(x, y, str[i]));
}
else if (str[i] == ',' || str[i] == ' ')
continue;
else
mystack.push(str[i] - '0');
}
return mystack.top();
}
int doCalculation(int x, int y, char c)
{
switch (c)
{
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
}
}
private:
string str;
stack<int> mystack;
};
void main()
{
string str = "4,5,*,1,2,+,+";
PolishExp pe(str);
cout << pe.calculation();
}