算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
**
输入格式:
**
输入在一行中给出不含空格的中缀表达式,可包含+、-、*、\以及左右括号(),表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
折磨我很久的一道题,数据结构真滴恐怖,把最开始没想到和出错的地方都注释了。
后面看了很多博主的都是string转double,也是一种好方法,但是当时觉得不用转也可以直接做,徒增了很多麻烦。。。如果不转double的话,就意味着超过10以上的数会分两次输出,所以要判断一下,不能让40,输出成4 0.
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
#include <stack>
using namespace std;
stack<char> ch;
stack<char> tmp;
int main()
{
string a;
cin>>a;
int flag=0;
int flag2=0;
for(int i=0; a[i]; i++)
{
if(a[i]>='0'&&a[i]<='9')
{
if(flag==0&&flag2==0)
{
cout<<a[i];
flag=1;
}
else if(a[i-1]>='0'&&a[i-1]<='9')
{
cout<<a[i];
}
else if(a[i-1]=='.')
{
cout<<"."<<a[i];
}
else
{
cout<<" "<<a[i];
}
//cout<<"flag1"<<endl;
}
else if(a[i]=='+'||a[i]=='-')
{
if (i==0||(!ch.empty()&&(a[i-1]<='0'||a[i-1]>='9')&&a[i-1]!=')'))//如果输入的数字前面有正负号,i==0意思是这种情况:-2+3*(8-4)。另一种情况是:-2+3*(8/(-40))
{
if(a[i]=='-')
{
if(i==0)
{cout<<a[i]<<a[i+1];
flag2=1;}
else
cout<<" "<<a[i]<<a[i+1];
i++;
}
else
continue;
}
else if(ch.empty())
{
ch.push(a[i]);
}
else
{
while(1)
{
if(!ch.empty()&&ch.top()!='(')
{
cout<<" "<<ch.top();
ch.pop();
}
else
break;
}
ch.push(a[i]);
}
//cout<<"flag2"<<endl;
}
else if(a[i]=='/'||a[i]=='*')
{
if(ch.empty())
{
ch.push(a[i]);
}
else if(ch.top()=='/'||ch.top()=='*')
{
while(1)
{
if(ch.top()=='/'||ch.top()=='*'||!ch.top()=='(')
{
cout<<" "<<ch.top();
ch.pop();
}
else
break;
}
ch.push(a[i]);
}
else
{
ch.push(a[i]);
}
//cout<<"flag3"<<endl;
}
else if(a[i]=='(')//最高优先级
{
ch.push(a[i]);
//cout<<"flag4"<<endl;
}
else if(a[i]==')')
{
while(1)
{
if(ch.top()!='(')
{
cout<<" "<<ch.top();
ch.pop();
}
else
{
ch.pop();
break;
}
}
// cout<<"flag5"<<endl;
}
}
while(!ch.empty())
{
if(ch.top()=='(')
ch.pop();
else
{
cout<<" "<<ch.top();
ch.pop();
}
//cout<<"flag6"<<endl;
}
return 0;
}