描述
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。
样例输入
2
1.000+2/4=
((1+2)*5+1)/4=
样例输出
1.000 2 4 / + =
//用到栈的地方一定要小心栈越界,血淋淋的教训,提交了很久都是 runtimeerror;
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式的中缀式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。
数据保证除数不会为0
输出
每组都输出该组中缀式相应的后缀式,要求相邻的操作数操作符用空格隔开。
样例输入
2
1.000+2/4=
((1+2)*5+1)/4=
样例输出
1.000 2 4 / + =
1 2 + 5 * 1 + 4 / =
#include<stdio.h>
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int judge(char c)
{
if(c=='*'||c=='/')
return 2;
else if(c=='+'||c=='-')
return 1;
return 0;
}
bool isoperation(char c)
{
if(c=='+'||c=='-'||c=='*'||c=='/')
return 1;
return 0;
}
string convert(string str)
{
stack<char> st;
string tmp="";
int i,len=str.length();
for(i=0;str[i]!='='&&i<len;i++)
{
if(str[i]=='(')
st.push(str[i]);
else if(str[i]==')')
{
while(!st.empty()&&st.top()!='(')
{
tmp+=st.top();
tmp+=' ';
st.pop();
}
st.pop();
}
else if(isoperation(str[i]))
{
if(st.empty()!=1)
{
while(!st.empty()&&judge(st.top())>=judge(str[i]))
{
tmp+=st.top();
tmp+=' ';
st.pop();
}
st.push(str[i]);
}
else
st.push(str[i]);
}
else
{
while(str[i]>='0'&&str[i]<='9'||str[i]=='.')
tmp+=str[i++];
i--;
tmp+=' ';
}
}
while(!st.empty())
{
tmp+=st.top();
tmp+=' ';
st.pop();
}
tmp+='=';
return tmp;
}
int main()
{
//freopen("b.txt","r",stdin);
int t;
string ep;
scanf("%d",&t);
while(t--)
{
cin>>ep;
cout<<convert(ep)<<endl;
}
return 0;
}
//用到栈的地方一定要小心栈越界,血淋淋的教训,提交了很久都是 runtimeerror;