数据结构实验之栈二:一般算术表达式转换成后缀式

mac2022-06-30  29

题目描述

对于一个基于二元运算符的算术表达式,转换为对应的后缀式,并输出之。

输入

输入一个算术表达式,以‘#’字符作为结束标志。

输出

输出该表达式转换所得到的后缀式。

示例输入

a*b+(c-d/e)*f#

示例输出

ab*cde/-f*+ 1 #include<stdio.h> 2 #include<string.h> 3 int main() 4 { 5 char s[101],st[101]; 6 int top; 7 top = -1; 8 scanf("%s",s); 9 for(int i = 0; s[i]!= '#'; i++) 10 { 11 if(s[i] >= 'a' && s[i] <= 'z') 12 printf("%c",s[i]);//数字直接输出 13 else if(s[i] == '(') 14 st[++top] = s[i];//左括号直接进栈 15 else if(s[i] == ')') 16 { 17 while(st[top] != '(') 18 { 19 printf("%c",st[top]); 20 top--; 21 } 22 top--; 23 }//将栈中元素输出直到遇到左括号,再将左括号出栈 24 else if(s[i] == '+' || s[i] == '-') 25 { 26 while(top != -1 && st[top] != '(') 27 { 28 printf("%c",st[top]); 29 top--; 30 } 31 st[++top] = s[i];将左括号之后的输出后再将是s[i]进栈。 32 } 33 else if(s[i] == '*' || s[i] == '/') 34 { 35 while(top != -1 && st[top] != '('&&(st[top] == '*'||st[top] == '/')) 36 { 37 printf("%c",st[top]); 38 top--; 39 } 40 st[++top] = s[i]; 41 } 42 } 43 while(top != -1) 44 { 45 printf("%c",st[top]); 46 top--; 47 }最后将栈中元素全部出栈 48 printf("\n"); 49 return 0; 50 } View Code

 

转载于:https://www.cnblogs.com/LK1994/p/3151837.html

相关资源:JAVA上百实例源码以及开源项目
最新回复(0)