算术表达式有前缀表示法、中缀表示法和后缀表示法等形式。日常使用的算术表达式是采用中缀表示法,即二元运算符位于两个运算数中间。请设计程序将中缀表达式转换为后缀表达式。
输入格式:
输入在一行中给出不含空格的中缀表达式,可包含+
、-
、*
、\
以及左右括号()
,表达式不超过20个字符。
输出格式:
在一行中输出转换后的后缀表达式,要求不同对象(运算数、运算符号)之间以空格分隔,但结尾不得有多余空格。
输入样例:
2+3*(7-4)+8/4
输出样例:
2 3 7 4 - * + 8 4 / +
#include<iostream>
#include<string>
#include<map>
#include<stack>
using namespace std;
int main()
{
string a;
stack<char>s;
int c=0,printk=0;
cin>>a;
map<char,int>p;
p['*']=p['/']=1;
p['(']=p[')']=2;
for(int i=0;i<a.length();i++)
{
if((i<1||a[i-1]=='(')&&(a[i]=='+'||a[i]=='-')||a[i]=='.'||a[i]>='0'&&a[i]<='9')
{
if(printk)
{
cout<<" ";
}
printk++;
if(a[i]!='+')cout<<a[i];
while(a[i+1]=='.'||a[i+1]>='0'&&a[i+1]<='9')
{
i++;
cout<<a[i];
}
}
else
{
if(a[i]==')')
{
while(s.size()>0&&s.top()!='(')
{
cout<<" "<<s.top();
s.pop();
}
s.pop();
}
else if(s.size()==0||p[a[i]]>p[s.top()])
{
s.push(a[i]);
}
else
{
while(s.size()>0&&s.top()!='(')
{
cout<<" "<<s.top();
s.pop();
}
s.push(a[i]);
}
}
}
while(s.size())
{
cout<<" "<<s.top();
s.pop();
}
}