中序表达式的概念:又称前缀表达式,不含括号的表达式,而且他将运算符写在前面,操作数写在后面,并且没有算术优先级,也称“波兰式”
优点:计算机可以从右到左扫描运算,不需要考虑算术优先级问题。
PS:原创,如有错误,请指出,感谢指教!
(一)、中序表达式转前序表达式
步骤:
1、先将中序表达式反转,然后转换成字符数组
2、依次取得字符数组的每一个元素,直至取完
若该元素为数字,则添加到可变字符串str中
若该元素为右括号,则入ops栈(运算符栈)
若该元素为左括号,则依次取出ops栈中元素,添加到str中,直至遇到右括号,右括号出栈
若该元素为运算符:
当栈顶为空时,或者取出元素优先级高于或等于栈顶元素时,或者栈顶为右括号时,该元素入栈
反之,栈顶元素出栈,添加到str中,直至满足上一条语句条件
3、当栈顶不为空时,依次取出栈顶元素,添加到str中,直至栈顶为空
4、最后,将str反转,得到前序表达式
代码:
1 package 表达式求值; 2 3 import java.util.Stack; 4 5 public class CenterToBefore { 6 7 public static String transform(String s){ 8 StringBuilder str = new StringBuilder(s); 9 StringBuilder st = new StringBuilder(); 10 str.reverse(); //将字符串反转 11 Stack<Character> ops = new Stack<>(); //运算符栈 12 for(int i = 0; i < str.length(); i++){ 13 char ch = str.charAt(i); 14 if(ch >= '0' && ch <= '9'){ 15 st.append(ch); 16 } 17 else if(ch == ')'){ 18 ops.push(ch); 19 } 20 else if(ch == '('){ 21 while(true){ 22 ch = ops.pop(); 23 if(ch == ')'){ 24 break; 25 } 26 else{ 27 st.append(ch); 28 } 29 } 30 } 31 else{ 32 while(true){ 33 if(ops.isEmpty()){ 34 ops.push(ch); 35 break; 36 } 37 char c = ops.peek(); 38 if(ops.peek() == ')' || ((c == '+' || c == '-') || (ch == '*' || ch == '/'))){ 39 ops.push(ch); 40 break; 41 } 42 st.append(ops.pop()); 43 } 44 } 45 } 46 while(!ops.isEmpty()){ 47 st.append(ops.pop()); 48 } 49 st.reverse(); 50 return st.toString(); 51 } 52 53 public static void main(String[] args) { 54 System.out.println(transform("((1+2)*3)*5+4+(2+3)*3")); 55 } 56 }
(二)、前序表达式求值
(1)步骤:
1、先将前序表达式转成字符数组
2、依次取得字符数组的每一个元素(从最后一个取到第一个),直至取完
若该元素为数字,则入num栈,
若该元素为运算符,则将栈顶元素和下一个元素出栈,并按该运算符依次计算,将结果入num栈。
3、最后返回num栈顶元素,该元素即为前序表达式运算结果
(2)代码:
1 package 表达式求值; 2 3 import java.util.Stack; 4 5 public class CenterToBefore { 6 7 public static String transform(String s){ 8 StringBuilder str = new StringBuilder(s); 9 StringBuilder st = new StringBuilder(); 10 str.reverse(); //将字符串反转 11 Stack<Character> ops = new Stack<>(); //运算符栈 12 for(int i = 0; i < str.length(); i++){ 13 char ch = str.charAt(i); 14 if(ch >= '0' && ch <= '9'){ 15 st.append(ch); 16 } 17 else if(ch == ')'){ 18 ops.push(ch); 19 } 20 else if(ch == '('){ 21 while(true){ 22 ch = ops.pop(); 23 if(ch == ')'){ 24 break; 25 } 26 else{ 27 st.append(ch); 28 } 29 } 30 } 31 else{ 32 while(true){ 33 if(ops.isEmpty()){ 34 ops.push(ch); 35 break; 36 } 37 char c = ops.peek(); 38 if(ops.peek() == ')' || ((c == '+' || c == '-') || (ch == '*' || ch == '/'))){ 39 ops.push(ch); 40 break; 41 } 42 st.append(ops.pop()); 43 } 44 } 45 } 46 while(!ops.isEmpty()){ 47 st.append(ops.pop()); 48 } 49 st.reverse(); 50 return st.toString(); 51 } 52 53 public static void main(String[] args) { 54 System.out.println(transform("((1+2)*3)*5+4+(2+3)*3")); 55 } 56 }