中缀转前缀(数值可以是小数类型和超过一位的整数)

/*

*/
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <map>
#include <vector>
#include <set>
#include<stdlib.h>//atof函数头文件
#include <bitset>
#include <stack>
#define ull unsigned long long
#define mems(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
const ll mod=100000007;
const double pi=acos(-1);
stack<char>op;
stack<char>q;
stack<double>qq;
char s[11000],s1[11000],s2[11000],s3[11000];
int priority(char ch)
{
    if(ch=='(')
        return 0;
    if(ch=='+'||ch=='-')
        return 1;
    if(ch=='*'||ch=='/')
        return 2;
    return -1;
}
int main()
{
    int t;
    scanf("%d",&t);
    op.push('#');
    while(t--)
    {
        scanf("%s",s1);
        int len=strlen(s1);
        int p=-1;
        for(int i=len-1; i>=0; i--) //中缀转前缀,从后向前扫;后缀是从前向后扫
        {
            if((s1[i]>='0'&&s1[i]<='9')||s1[i]=='.')
            {
                s2[++p]=s1[i];
            }
            else if(s1[i]=='+'||s1[i]=='-'||s1[i]=='*'||s1[i]=='/')
            {
                if(priority(s1[i])>=priority(op.top()))//优先级大于或等于栈顶优先级
                {                                      //后缀是大于,没有等于
                    s2[++p]=' ';
                    op.push(s1[i]);
                    //printf("%c\n",s1[i]);
                }
                else
                {
                    while(priority(s1[i])<priority(op.top()))//优先级小于栈顶优先级
                    {                                        //后缀是小于等于
                        s2[++p]=' ';
                        s2[++p]=op.top();
                        op.pop();
                    }
                    s2[++p]=' ';
                    op.push(s1[i]);
                }
            }
            else if(s1[i]==')')
            {
                //s2[++p]=' ';
                op.push(s1[i]);
            }
            else if(s1[i]=='(')
            {
                while(op.top()!=')')
                {
                    s2[++p]=' ';
                    s2[++p]=op.top();
                    op.pop();
                }
                //s2[++p]=' ';
                op.pop();
            }

        }
        while(op.top()!='#')
        {
            s2[++p]=' ';
            s2[++p]=op.top();
            op.pop();
        }
        for(int i=p; i>=0; i--)
        {
            printf("%c",s2[i]);
        }
        printf(" =\n");
    }
    return 0;
}


/*
3
1+(3+2)*(7^2+6*9)/(2)
(6*2)^0/2
6*2^0/2
*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值