表达式求值训练 E 中缀式变后缀式

表达式求值训练



E 中缀式变后缀式


内存限制:64MB  时间限制:1s  Special Judge: No

题目描述:

人们的日常习惯是把算术表达式写成中缀式,但对于机器来说更“习惯于”后缀式,关于算术表达式的中缀式和后缀式的论述一般的数据结构书都有相关内容可供参看,这里不再赘述,现在你的任务是将中缀式变为后缀式。

输入描述:

第一行输入一个整数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<cstdio>
#include<cstring>
#include<stack>
#include<cmath>
#include<algorithm>
using namespace std;
char str[1100];
int compare(char i)
{
    if(i=='+'||i=='-')return 1;
    if(i=='*'||i=='/')return 2;
    if(i=='(')return 0;
    return -1;
}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        memset(str,'\0',sizeof(str));
        scanf("%s",str);
        int len=strlen(str);
        double n1=0,n2=0,n3=0,n4=0;
        stack<char> s;
        s.push('#');
        for(int i=0;i<len-1;i++)
        {
            n1=0;n2=0;n3=0;n4=1;
            while(isdigit(str[i])||str[i]=='.')
            {
                if(str[i]=='.'){cout<<str[i];n3=1;i++;}
                if(n3==0)cout<<str[i];
                else {
                    cout<<str[i];
                }
                n2=1;
                if(isdigit(str[i+1])||str[i+1]=='.')i++;
                else break;
            }
            if(n2==1){
                cout<<" ";
            }
            else if(str[i]=='('){
                s.push(str[i]);
            }
            else if(str[i]==')'){
                while(s.top()!='(')
                {
                    cout<<s.top()<<" ";
                    s.pop();
                }
                s.pop();
            }
            else{
                while(compare(s.top())>=compare(str[i]))
                {
                    cout<<s.top()<<" ";
                    s.pop();
                }
                s.push(str[i]);
            }
        }
        while(s.top()!='#'){
            cout<<s.top()<<" ";
            s.pop();
        }
        cout<<'='<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40788630/article/details/80424215