题目描述:
人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。
输入描述:
第一行输入一个整数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<iostream>
#include<stack>
#include<string>
using namespace std;
string s,str;
int yxj(char ch)
{
switch(ch)//判断运算符的优先级
{
case'+':
case'-':
return 1;
case'*':
case'/':
return 2;
default:
return 0;
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>s;
stack<char>pq;
pq.push('#');
int len=s.size(),i=0;
str.clear();//将栈清空
while(i<len-1)//把等于号先剔除,最后再加上
{
if(s[i]=='(')//如果碰到左括号,将其放入栈内
{
pq.push(s[i]);
i++;
}
else if(s[i]==')')//碰到右括号时,将右括号到左括号内的数字输出,不输出左括号
{
while(pq.top() !='(')
{
str+=pq.top();
pq.pop();
str+=' ';
}
pq.pop();
i++;
}
else if(s[i]=='+'||s[i]=='-'||s[i]=='*'|s[i]=='/')//当碰到运算符号的时候,按优先级存入栈中
{
while(yxj(pq.top())>=yxj(s[i]))
{
str+=pq.top();
str+=' ';
pq.pop();
}
pq.push(s[i]);
i++;
}
else
{
while(s[i]>='0'&&s[i]<='9'||s[i]=='.')//碰到数字时,将数字输出
{
str+=s[i];
i++;
}
str+=' ';
}
}
while(pq.top()!='#')//将栈中剩余的东西掏空
{
str+=pq.top();
pq.pop();
str+=' ';
}
str+='=';//最后加上等于号
cout<<str<<"\n";
}
return 0;
}
错误代码:(我也不知道哪错了。。)
#include<stdio.h>
#include<string.h>
#include<stack>
#include<queue>
using namespace std;
int oper(char op){
if(op=='+'||op=='-')
return 1;
if(op=='*'||op=='/')
return 2;
return 0;//操作符为'('时
}//输出操作符优先级
int main(){
int n,len,i;
char str[1005];
scanf("%d\n",&n);
while(n--){
stack <char> ch;//操作符栈
queue <char> num;//数字队列,此队列也用来存放输出顺序
gets(str);
len=strlen(str);
for(i=0;i<len-1;){ //中缀转后缀
if(str[i]=='(')
{
ch.push(str[i]);
i++;
}
else if(str[i]==')'){
while(ch.top()!='('){
num.push(ch.top());
ch.pop();
num.push(' ');
}
ch.pop();//去括号'('
i++;
}
else if(str[i]=='+'||str[i]=='-'||str[i]=='*'||str[i]=='/')
{
while(oper(str[i])<=oper(ch.top())){//操作符入队列,直到优先级大于栈顶为止
num.push(ch.top());
ch.pop();
num.push(' ');
}
ch.push(str[i]);
i++;
}
else
{
while(str[i]>='0'&&str[i]<='9'||str[i]=='.')
{
num.push(str[i]);
i++;
}
num.push(' ');
}
}
while(!ch.empty()){//处理剩余操作符
num.push(ch.top());
ch.pop();
num.push(' ');
}
while(!num.empty()){//输出队列
printf("%c",num.front());
num.pop();
}
printf("=\n");
}
return 0;
}