1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 中缀转后缀表达式(C语言实现)

中缀转后缀表达式(C语言实现)

时间:2020-05-12 04:15:40

相关推荐

中缀转后缀表达式(C语言实现)

实现效果

源码

#include<stdio.h>#include<string.h>//创建栈 typedef struct node{char s[1000];int top;}Stack;//判断符号的函数 int weight(char ch, int flag){if(ch=='+'||ch=='-') return 1;if(ch=='*'||ch=='/') return 2;if(ch=='('&&flag==1) return 0;if(ch=='('&&flag==0) return 3;}//准换函数 void transform(char str[]){Stack a;a.top=-1;int i,f=0,m=strlen(str);for(i=0;i<m;i++){if(str[i]>='A'&&str[i]<'Z')//遍历 {printf("%c",str[i]);}else{if(a.top==-1){a.s[++a.top]=str[i];continue;}if(str[i]==')'){while(a.top!=-1&&a.s[a.top]!='(') // 每次进行出栈操作时都要判断栈是否为空,且判断在操作之前。printf("%c",a.s[a.top--]);--a.top;continue;}if(weight(str[i],0)>weight(a.s[a.top],1)){a.s[++a.top]=str[i];continue;}while(a.top!=-1&&weight(str[i],0)<=weight(a.s[a.top],1)) //每次进行出栈操作时都要判断栈是否为空,{//且判断在操作之前。printf("%c",a.s[a.top]);// 用while循环为不用if语句来比较新读入的操作符与栈顶操作的的权值大小,--a.top; // 是因为当新读入的操作符的权值小于栈顶操作符的权值时,也可能小于栈顶f=1; // 下一 个操作符的权值}if(f==1){a.s[++a.top]=str[i];f=0;}}}while(a.top!=-1){printf("%c",a.s[a.top--]);}}int main(){char str[310];gets(str);transform(str);return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。