栈的应用之中缀表达式转换为后缀表达式
2016-10-02 13:50
363 查看
//思路: //1:当读到一个操作数,立即放到后缀表达式结果中。 //2:当读到一个操作符,从存储运算符的栈中弹出元素到后缀表达式结果,直到出现级别更低的运算符为止, //最后再把此运算符推入栈, //但有一个例外,除非遇到),否者绝不会弹出(。 //3:当读到一个(,压入栈中。 //示例: //中缀:a + b * c + ( d * e + f ) * g //后缀:a b c * + d e * f + g * + #include <stdio.h> #include <stdlib.h> //假设输入的中缀表达式各运算符和运算数之间均存在空格,且中缀表达式合法 char temp[100];//临时存储操作符 int topt=-1; char result[100];//存储后缀表达式结果 int topr=-1; int isoperator(char data[]) { if(strlen(data)!=1) return 0; switch(data[0]) { case '+': case '-': case '*': case '/': case '(': case ')':return 1; default:return 0; } } void dealtemp(char data[]) { if(data[0]==')'){ while(temp[topt]!='('){ result[++topr]=' '; result[++topr]=temp[topt]; topt--; } topt--; } else if(data[0]=='*'||data[0]=='/'){ while(topt!=-1&&temp[topt]!='('&&temp[topt]!='+'&&temp[topt]!='-'){ result[++topr]=' '; result[++topr]=temp[topt]; topt--; } temp[++topt]=data[0]; } else if(data[0]=='+'||data[0]=='-'){ while(topt!=-1&&temp[topt]!='('){ result[++topr]=' '; result[++topr]=temp[topt]; topt--; } temp[++topt]=data[0]; } else{ temp[++topt]=data[0]; } } int main() { //用两个栈实现转变 char data[100];//原始的中缀数据 int flag=0;//决定当前字符串前添不添加空格 while(scanf("%s",data)!=EOF){ if(isoperator(data)){//判断是不是操作符 dealtemp(data); } else{ if(flag) result[++topr]=' '; strcpy(result+topr+1,data); topr=strlen(result)-1; flag=1; } } while(topt!=-1){ result[++topr]=' '; result[++topr]=temp[topt--]; } result[++topr]='\0'; puts(result); return 0; }
相关文章推荐
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 栈的应用 平衡符号 后缀表达式 中缀到后缀的转换
- 栈的应用:中缀和后缀表达式的转换及计算
- (转)前缀、中缀、后缀表达式及转换与应用
- 栈应用之将中缀数值表达式转换成后缀表达式
- 堆栈的应用(2) 中缀算术表达式到后缀(逆波兰记法reverse polish notation)的转换及其计算 C++实现
- 栈的应用— 中缀表达式到后缀表达式的转换
- 中缀表达式转换成后缀表达式
- 栈的应用实例——中缀表达式转换为后缀表达式
- 数据结构——从中缀向后缀转换表达式
- [栈和队列]从中缀向后缀转换表达式
- 中缀表达式到后缀表达式的转换
- 中缀到后缀表达式的转换
- 中缀后缀表达式的转换
- 栈的应用:中缀表达式转为后缀表达式(c语言实现)
- 中缀表达式转换为前缀及后缀表达式并求值【摘】
- 中缀、前缀、后缀表达式之间的转换
- 中缀/后缀表达式转换-使用四则混合运算表达式生成树
- 表达式求值,中缀后缀转换,表达式递归直接求值等相关算法的实现
- [栈和队列]从中缀向后缀转换表达式