#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<char> s; // use a stack to store the character of the equation
string equation; // store the whole equation
getline (cin, equation);
int cur = 0; // the current position in the equation
while (cur < equation.size())
{
while (equation[cur] == ' ')
cur++;
if (equation[cur] >= 'a' && equation[cur] <= 'z')
cout<< equation[cur] << " ";
else if (equation[cur] == ')')
{
while(!s.empty() && s.top() != '(') // if equation[cur] equals ')', then pop out all the character until '('
{
cout<< s.top() << " ";
s.pop();
}
s.pop(); // pop out the '('
}
else if (equation[cur] == '(') // '(' has the highest priority, put it into the stack directly
s.push(equation[cur]);
else if (equation[cur] == '^') // '^' has the highest priority except for the parenthesis
s.push(equation[cur]);
else if (equation[cur] == '*' || equation[cur] == '/') //
{
while(!s.empty() && s.top() != '+'&& s.top() != '-' && s.top() != '(') //'*' and '/' have the same priority
{
cout<< s.top() << " ";
s.pop();
}
s.push(equation[cur]);
}
else if (equation[cur] == '+' || equation[cur] == '-') //'+' and '-' have the same priority
{
while(!s.empty() && s.top() != '(' )
{
cout<< s.top() << " ";
s.pop();
}
s.push(equation[cur]);
}
cur++; // to process the next character
}
while (!s.empty())
{
cout << s.top() << " ";
s.pop();
}
return 0;
}
infix2postfix
最新推荐文章于 2020-04-13 01:07:06 发布