java实现中缀表达式转后缀表达式
1 package postfix; 2 3 import java.util.Stack; 4 5 /** 6 * 7 * @author DELL 将中缀表达式转化为后缀表达式 8 */ 9 10 public class Expression { 11 private StringBuffer iExp; // 存储中缀表达式 12 private Stack stack; 13 private StringBuffer pExp; // 存储后缀表达式 14 15 public Expression(String s) { 16 iExp = new StringBuffer(s); 17 stack = new Stack(); 18 pExp = new StringBuffer(); 19 } 20 21 public String toPostfix() throws Exception { 22 while (iExp.length() != 0) { 23 char c = iExp.charAt(0); 24 iExp.deleteCharAt(0); 25 switch (c) { 26 case '0': 27 case '1': 28 case '2': 29 case '3': 30 case '4': 31 case '5': 32 case '6': 33 case '7': 34 case '8': 35 case '9': 36 pExp.append(c); 37 break; 38 case '(': 39 stack.push(c); 40 break; 41 case ')': 42 while (stack.peek() != (Object) '(') { 43 pExp.append(stack.pop()); 44 } 45 stack.pop(); 46 break; 47 case '+': 48 case '-': 49 while (!stack.isEmpty() && stack.peek() != (Object) '(') { 50 pExp.append(stack.pop()); 51 } 52 stack.push(c); 53 54 break; 55 case '*': 56 case '/': 57 while (!stack.isEmpty() && stack.peek() != (Object) '(' && stack.peek() != (Object) '+' 58 && stack.peek() != (Object) '-') { 59 pExp.append(stack.pop()); 60 } 61 stack.push(c); 62 break; 63 case '^': 64 stack.push('^'); 65 break; 66 default: 67 System.out.println("出现错误字符"+c); 68 break; 69 } 70 71 } 72 while (!stack.isEmpty()) { 73 pExp.append(stack.pop()); 74 } 75 return pExp.toString(); 76 } 77 78 }
撰写时间:2017-08-13 16:50:11
修改时间:
越学习越发现自己的无知