SDUT2484 算术表达式的转换

这是一个将中缀式转化成表达式树然后在遍历输出的题

代码操作总结为:

1、把中缀式转换为后缀式。

2、把后缀式转化为表达式树。

3、将表达式树先序、中序、后序遍历得出前缀式、中缀式、后缀式。


以下是代码:

#include <stdio.h>
#include <malloc.h>
struct node
{
    char s;
    struct node *l,*r;
};
char sa[100],sb[100],sc[100];
int p;
void first(struct node *q)
{
    if(q==NULL)
    {
        return ;
    }
    printf("%c",q->s);
    first(q->l);
    first(q->r);
}
void infix(struct node *q)
{
    if(q==NULL)
    {
        return ;
    }
    infix(q->l);
    printf("%c",q->s);
    infix(q->r);
}
void postfix(struct node *q)
{
    if(q==NULL)
    {
        return ;
    }
    postfix(q->l);
    postfix(q->r);
    printf("%c",q->s);
}
void h()
{
    int x=0,y=0;
    for(p=0; sa[p]!='#'; p++)
    {
        if(sa[p]>='a'&&sa[p]<='z')///如果是数字
        {
            sb[x]=sa[p];
            x++;
        }
        else if(sa[p]=='+'||sa[p]=='-')
        {
            while(y!=0&&sc[y-1]!='(')
            {
                sb[x]=sc[y-1];
                x++;
                y--;
            }
            sc[y]=sa[p];
            y++;
        }
        else if(sa[p]=='*'||sa[p]=='/')
        {
            while(y!=0&&(sc[y-1]=='*'||sc[y-1]=='/'))
            {
                sb[x]=sc[y-1];
                x++;
                y--;
            }
            sc[y]=sa[p];
            y++;
        }
        else if(sa[p]=='(')
        {
            sc[y]=sa[p];
            y++;
        }
        else if(sa[p]==')')
        {
            while(sc[y-1]!='(')
            {
                sb[x]=sc[y-1];
                x++;
                y--;
            }
            y--;
        }
    }
    while(y!=0)
    {
        sb[x]=sc[y-1];
        x++;
        y--;
    }
    sb[x]='\0';
}
int main()
{
    int d=0,i;
    scanf("%s",sa);
    h();
    struct node *po[100]={NULL},*pi;
    for(i=0;i<p;i++)
    {
        if(sb[i]>='a'&&sb[i]<='z')
        {
            pi=(struct node *)malloc(sizeof(struct node));
            pi->s=sb[i];
            pi->l=NULL;
            pi->r=NULL;
            po[d]=pi;
            d++;
        }
        else
        {
            pi=(struct node *)malloc(sizeof(struct node));
            pi->s=sb[i];
            pi->r=po[d-1];
            d--;
            pi->l=po[d-1];
            d--;
            po[d]=pi;
            d++;
        }
    }
    first(po[0]);
    printf("\n");
    infix(po[0]);
    printf("\n");
    postfix(po[0]);
    printf("\n");
    return 0;
}



转载于:https://www.cnblogs.com/lin375691011/p/3996778.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值