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