SDUT2484 算术表达式的转换
2013-07-18 19:29
176 查看
这是一个将中缀式转化成表达式树然后在遍历输出的题
代码操作总结为:
1、把中缀式转换为后缀式。
2、把后缀式转化为表达式树。
3、将表达式树先序、中序、后序遍历得出前缀式、中缀式、后缀式。
以下是代码:
代码操作总结为:
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; }
相关文章推荐
- SDUT 2484 算术表达式的转换
- SDUT2484 算术表达式的转换
- SDUT2484 算术表达式的转换(表达式树)
- SDUT2484算术表达式的转换
- SDUT 2484 算术表达式的转换
- sdutoj2484 算术表达式的转换 栈思想
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- SDUTOJ 2484 算术表达式的转换(表达式树)
- 数据结构实验之栈二:一般算术表达式转换成后缀式 SDUT
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- 数据结构实验之栈二:一般算术表达式转换成后缀式 SDUT 2132
- 暑假集训 8.6 sdutoj2484 算术表达式的转换(模拟栈;前中后缀转换)
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- SDUT2132--一般算术表达式转换成后缀式
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- [SDUT](2132)数据结构实验之栈二:一般算术表达式转换成后缀式 ---栈
- SDUT2132算术表达式转换成后缀式(表达式树)
- SDUT 2132 数据结构实验之栈二:一般算术表达式转换成后缀式
- SDUT算术表达式的转换(二叉树做法,建树及转换操作)
- 表达式的转换(sdut-2484)