考点:转换过程中同时保存在栈中的操作符的最大个数。
#include <bits/stdc++.h>
using namespace std;
map<char, int> isp; ///in stack priority
map<char, int> icp; ///in coming priority
void init()
{
isp['('] = 1;
isp[')'] = 6;
isp['+'] = 3;
isp['-'] = 3;
isp['*'] = 5;
isp['/'] = 5;
icp['('] = 6;
icp[')'] = 1;
icp['+'] = 2;
icp['-'] = 2;
icp['*'] = 4;
icp['/'] = 4;
}
bool checkIfOperator(char ch)
{
switch(ch)
{
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
return true;
default:
return false;
}
}
string Infix2Postfix(string infix)
{
stack<char> op;
string postfix = "";
int len = infix.length();
for(int i = 0; i < len ;++i)
{
if(checkIfOperator(infix[i]))
{
if(infix[i] == '(')
op.push(infix[i]);
else if(infix[i] == ')')
{
while(!op.empty() && op.top() != '(')
{
postfix += op.top();
op.pop();
}
op.pop();
}
else
{
if(op.empty() || icp[ infix[i] ] > isp[ op.top() ])
op.push(infix[i]);
else
{
while(!op.empty() && icp[ infix[i] ] <= isp[ op.top() ])
{
postfix += op.top();
op.pop();
}
}
}
}
else
postfix += infix[i];
}
while(!op.empty())
{
postfix += op.top();
op.pop();
}
return postfix;
}
int main()
{
init();
string infix = "";
cin >> infix;
cout << Infix2Postfix(infix);
return 0;
}