一年前转载,忘记谁写的了。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int prio(char op) //运算符优先级排序
{
int priority;
if (op == '*' || op == '/')
priority = 2;
if (op == '+' || op == '-')
priority = 1;
if (op == '(')
priority = 0;
return priority;
}
bool Trans(string &str,string &str1) //引用传递
{
stack<char> s;
int i;
for (i = 0; i<str.size(); i++)
{
if (str[i] >= '0' && str[i] <= '9'||str[i] >= 'a' && str[i] <= 'z')
{
str1+=str[i];
}
else
{
if (s.empty())
s.push(str[i]);
else if (str[i] == '(')
s.push(str[i]);
else if (str[i] == ')')
{
while (s.top() != '(')
{
str1+= s.top();
s.pop();
}
s.pop();
}
else
{
while (prio(str[i]) <= prio(s.top()))
{
str1+= s.top();
s.pop();
if (s.empty())
break;
}
s.push(str[i]);
}
}
}
while (!s.empty())
{
str1+= s.top();
s.pop();
}
return true;
}
int main()
{
string infix;
string postfix;
cout << "请输入中缀表达式:" << infix << endl;
cin >> infix;
Trans(infix,postfix);
cout << "后缀表达式为:" << postfix << endl;
system("pause");
return 0;
}