中缀表达式转后缀表达式
中缀表达式转后缀表达式对于计算机专业的学生来说几乎是要人人掌握的,不过要把其中的脉络理清楚,对于编程能力一般的童鞋来说,还是有点小难度的。
先贴一个地址,http://pal.cndev.org/2005/10/13/44016/,这篇文章对于中缀转后缀的算法讲解的还算比较清楚了。
再贴代码,这是利用STL中的stack来实现的。
#include <iostream>
#include <stack>
using namespace std;
int main()
{
string infix_exp;
cin>>infix_exp;
int len = infix_exp.length();
stack<char> oper;
for(int i = 0; i < len; i++)
{
char ch = infix_exp[i];
if(ch < '9' && ch > '0')
cout<<ch;
if(ch == '+' || ch == '-')
{
if(oper.empty() || oper.top() == '(')
oper.push(ch);
else{
cout << oper.top();
oper.pop();
oper.push(ch);
}
}
if(ch == '*' || ch == '/')
{
if(oper.empty() || oper.top() == '(' || oper.top() == '+' || oper.top() == '-')
oper.push(ch);
else{
cout << oper.top();
oper.pop();
oper.push(ch);
}
}
if(ch == '(')
oper.push(ch);
if(ch == ')')
{
for(;;)
{
if(oper.top() == '(')
{
oper.pop();
break;
}
else{
cout << oper.top();
oper.pop();
}
}
}
}
while(!oper.empty())
{
cout << oper.top();
oper.pop();
}
cout << endl;
}

浙公网安备 33010602011771号