1.算法分析:
先存在某个地方。正确的做法是将已经见过的操作符放在栈中而不立即输出。当
遇到左圆括号时我们也要将其推入栈中。计算是从一个初始化为空的栈开始的。
如果遇见一个右括号,那么将栈中的元素弹出。将括号写出直到遇到对应的
括号,但是这个左括号只弹出而不输出。
如果见到任何其他的符号,那么从栈中弹出栈元素直到发现优先级更低的元
素为止。有一个例外:除非是在处理“)”的时候,否则觉不从栈中移走“(”。
对于这种操作,“+”的优先级最低,而“(”的优先级最高。当从栈中弹出元素的
工作结束后,我们再将操作符压入栈中。
最后,如果读到输入的末尾,将栈元素弹出直到该栈变为空栈,将符号写到
输出中。
例如,输入a+b*c+(d*e+f)*g,即可得到abc*+de*f+g
2.心得及体会:
在程序编写过程中遇到的最大问题毫无疑问是符号的同级与
优先级进入栈的问题。在处理同级的问题上,例如'+'与‘-',我
给予它们的symb分别为0.5与1,然后通过取整判断其差是否为零
来判断是否为同级。另外在print函数中,我又发现在switch中,
case后接的常量表达式必须为整数而不能为分数,这就迫使我在
读入symb的时候将其扩大十倍,才可以正确运行。
其次,在处理优先级问题,尤其是在遇到括号是也给我带来
了不小的麻烦。我通过引入flag这个变量来判断栈中是否读入了
’(‘,通过其值得改变成功的解决了这个问题。
最后,通过这个小程序的练习,让我对栈的有了更好的理解。
3.代码实现
<pre name="code" class="cpp">#include <iostream>
#include<string>
#include<stack>
using namespace std;
void print(int symb)
{
switch(symb)
{
case 5:cout<<'+';break;
case 10:cout<<'-';break;
case 30:cout<<'*';break;
case 25:cout<<'/';break;
case 45:cout<<'(';break;
case 50:cout<<')';break;
}
}
void infix_to_postfix(const string &equation)
{
char CH;
float symb;
cout<<"The postfix equation is:"<<endl;
cout<<"**********"<<endl;
stack<float>ST;int flag=0;
for(int i=0;(CH=equation[i])!='\0';i++)
{
switch(CH)
{
case'+':symb=0.5; break;
case'-':symb=1.0; break;
case'/':symb=2.5; break;
case'*':symb=3.0; break;
case'(':symb=4.5; break;
case')':symb=5.0; break;
default:cout.put(CH);symb=10;
}
if(symb<=5.0)
{
if(ST.empty()) ST.push(symb);
else
{ int j=ST.top()-symb;
if(ST.top()==4.5) flag=1;
if(!flag)
{
if(symb>ST.top()||j==0) ST.push(symb);
else
{
while(ST.size()>0)
{
print(ST.top()*10);
ST.pop();
}
ST.push(symb);
}
}
else
{
if(symb!=5.0)
{
if(ST.top()==4.5)ST.push(symb);
else if(symb>ST.top()||j==0) ST.push(symb);
else {while(ST.top()!=4.5)
{ print(ST.top()*10);ST.pop();}
ST.push(symb);}
}
else
{
while(ST.top()!=4.5)
{
print(ST.top()*10);ST.pop();
}
ST.pop();
flag=0;
}
}
}
}
}
while(ST.size()>0)
{
print(static_cast<int>(ST.top()*10));ST.pop();
}
}
int main()
{
string infix_equation;
cout<<"Please enter the infix equation:"<<endl;
cout<<"**********"<<endl;
getline(cin,infix_equation);
infix_to_postfix(infix_equation);
return 0;
}