中缀式变后缀式
时间限制:1000 ms | 内存限制:65535 KB
难度:3
描述
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入
第一行输入一个整数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 <bits/stdc++.h>
using namespace std;
int cmp[4][4]={//'+''-''*''/'的优先级 1表示栈顶比当前字符串的操作符优先级高
1,1,-1,-1,
1,1,-1,-1,
1,1,1,1,
1,1,1,1,
};
bool isnum(char c){//是否为小数或数字
if((c>='0'&&c<='9')||c=='.')
return true;
return false;
}
int atoi(char c){//ascii to int
if(c=='+') return 0;
if(c=='-') return 1;
if(c=='*') return 2;
if(c=='/') return 3;
}
int main(){
int n;
char s[1005];
cin>>n;
getchar();
while(n--){
stack<char>optr;
gets(s);
int len=strlen(s);
for(int i=0;i<len-1;i++){
int k=0;//标记是否输出过数字
while(isnum(s[i])){
cout<<s[i++];
k=1;
}
if(k) cout<<' ';
if(s[i]==')'){//如果当前为右括号则弹出栈顶符号并输出直到为左括号为止(括号不输出)
while(optr.top()!='('){
cout<<optr.top()<<' ';
optr.pop();
}
optr.pop();
}
else if(optr.size()==0||optr.top()=='('||s[i]=='('||cmp[atoi(optr.top())][atoi(s[i])]==-1){//入栈的情况
optr.push(s[i]);
}
else if(cmp[atoi(optr.top())][atoi(s[i])]==1){//如果栈顶元素优先级较高直接输出
cout<<optr.top()<<' ';
optr.pop();
i--;//字符串当前的操作符还要继续和栈里的运算符比较,i-1和循环的i+1抵消
}
}
while(optr.size()>0){
cout<<optr.top()<<' ';
optr.pop();
}
cout<<'='<<endl;
}
return 0;
}