【综合】中缀表达式转换成后缀表达式后,用后缀表达式计算出结果
2013-10-27 00:44
537 查看
本文是把前两个文章的代码综合了起来,为了调理清楚一点,所以另开设了一篇博客(纯代码):
#include<stdio.h> #include<malloc.h> #define StackMaxSize 30 typedef struct stack { char a[StackMaxSize]; int top; }STACK; int Pre(char op) { switch(op) { case '+': case '-': return 1; case '*': case '/': return 2; case '(': case '#': default: return 0; } } char *Change(char *s1) //中缀转换成后缀 { STACK s; int i=0,j=0; char ch,*s2; s2=(char *)malloc(sizeof(char)); s.top=-1; s.a[++s.top]='#'; ch=s1[i++]; while(ch!='#') { if(ch=='(') { s.a[++s.top]=ch; ch=s1[i++]; } else if(ch==')') { while(s.a[s.top]!='(') { s2[j++]=s.a[s.top--]; } s.top--; ch=s1[i++]; } else if(ch=='+'||ch=='-'||ch=='*'||ch=='/') { while(Pre(s.a[s.top])>=Pre(ch)) { s2[j++]=s.a[s.top--]; } s.a[++s.top]=ch; ch=s1[i++]; } else { s2[j++]=ch; ch=s1[i++]; } } ch=s.a[s.top--]; while(ch!='#') { s2[j++]=ch; ch=s.a[s.top--]; } s2[j++]='#'; return s2; } int Pre(char *s1) //后缀表达式的运算 { int i=0; int num1,num2,sum; STACK S; S.top=-1; while(s1[i]!='#') { if(s1[i]>='0' && s1[i]<='9') { s1[i]-=48; //因为现在是字符,所以要变成Int类型的值 S.a[++S.top]=s1[i]; } else { num1=S.a[S.top--]; num2=S.a[S.top--]; if(s1[i]=='+') sum=num2+num1; else if(s1[i]=='-') sum=num2-num1; else if(s1[i]=='*') sum=num2*num1; else if(s1[i]=='/') sum=num2/num1; S.a[++S.top]=sum; } i++; } printf("结果是:%d\n",S.a[S.top]); return S.a[S.top]; } void main() { int i=1,j=1; char c,*s1,*s2; s1=(char *)malloc(sizeof(char)); printf("请输入中缀表达式\n"); while((c=getchar())!='#') {s1[i++]=c;} s1[i]='#'; printf("\n"); s2=Change(s1); printf("转换后的后缀表达式\n"); while(s2[j]!='#') printf("%c",s2[j++]); printf("\n"); Pre(s2); }
相关文章推荐
- 中缀表达式转后缀表达式并输出计算结果
- 中缀表达式转换为后缀表达式&后缀表达式的计算
- 中缀表达式转换为后缀表达式 简易实现(c++)(简易表达式计算)
- 中缀表达式转为后缀表达式,并计算结果
- 中缀表达式转换成后缀表达式 计算后缀表达式的值 幂操作符添加到你的指令系统中去
- 数据结构实现中缀表达式到后缀表达式,再到计算出结果的代码
- Java实现中缀表达式转后缀表达式并计算结果
- 中缀表达式转换为后缀表达式,计算后缀表达式
- 中缀表达式与后缀表达式的转换及后缀表达式的计算
- 中缀表达式转后缀表达式 并计算后缀表达式
- C++栈的应用——后缀表达式求值、中缀表达式到后缀表达式的转换
- 中缀表达式转化为后缀表达式,并计算后缀表达式
- 学习日志-中缀表达式转后缀表达式并计算结果
- Java 中缀表达式转后缀表达式 + 中/后缀表达式计算
- 中缀表达式转换成后缀表达式,进行简单表达式的计算
- 中缀表达式转换为后缀表达式及逆波兰式计算
- C语言::将中缀表达式转换为后缀表达式并计算结果
- 中缀表达式转换成后缀表达式/计算后缀表达式
- 栈的应用 后缀表达式求值 后缀表达式与中缀表达式的转换
- 中缀表达式转后缀表达式并计算结果