您的位置:首页 > 其它

SDUT2484 算术表达式的转换

2013-07-18 19:29 176 查看
这是一个将中缀式转化成表达式树然后在遍历输出的题

代码操作总结为:

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: