zoukankan      html  css  js  c++  java
  • 算术表达式的转换

    ~题目连接~

    http://acm.sdut.edu.cn/sdutoj/showproblem.php?pid=2484&cid=1182

    输入

    a*b+(c-d/e)*f#
    结果
    +*ab*-c/def
    a*b+c-d/e*f
    ab*cde/-f*+

    小白书上有,表达式树
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #define maxn 1000+10
    
    int lc[maxn],rc[maxn],nc=0;//每个结点的左右儿子编号和字符
    char jc[maxn];//结点数
    
    //表达式树
    int build(char *s,int x,int y)
    {
        int i,c1 =-1,c2=-1,p=0,u;
        printf("%d %d
    ",x,y);
        if(y-x==1)
        {
            u=++nc;
            lc[u] = rc[u]=0;
            jc[u]=s[x];
            return u;
        }
        for(i=x; i<y; i++)//仅一个字符,建立单独结点
        {
            switch(s[i])
            {
            case '(':p++;break;
            case ')':p--;break;
            case '+':case '-':if(!p) c1=i;break;
            case '*':case '/':if(!p) c2=i;break;
            }
        }
        if(c1<0)
            c1=c2;//找不到括号外的加减号,就用乘除号
        if(c1<0)
            return build(s,x+1,y-1);//整个表达式被一对括号括起来
        u=++nc;
        lc[u]=build(s,x,c1);
        rc[u]=build(s,c1+1,y);
        jc[u]=s[c1];
        return u;
    }
    
    void preorder(int u)
    {
        if(u)
        {
            printf("%c",jc[u]);
            preorder(lc[u]);
            preorder(rc[u]);
        }
    }
    void inorder(int u)
    {
        if(u)
        {
            inorder(lc[u]);
            printf("%c",jc[u]);
            inorder(rc[u]);
        }
    }
    void postorder(int u)
    {
        if(u)
        {
            postorder(lc[u]);
            postorder(rc[u]);
            printf("%c",jc[u]);
        }
    }
    
    int main()
    {
        char s[maxn];
        scanf("%s",s);
        int u=build(s,0,strlen(s)-1);
        preorder(u);
        printf("
    ");
        inorder(u);
        printf("
    ");
        postorder(u);
        printf("
    ");
        return 0;
    }
    

      

      

  • 相关阅读:
    接口的幂等性原则
    SpringBoot热部署-解决方案
    @Resource 与 @Service注解的区别
    软件概要设计做什么,怎么做
    First Show
    Glide源码解析一,初始化
    android使用giflib加载gif
    android的APT技术
    RxJava的concat操作符
    RxJava基本使用
  • 原文地址:https://www.cnblogs.com/guoyongzhi/p/3233039.html
Copyright © 2011-2022 走看看