java实现中缀表达式转后缀表达式

时间:2023-03-08 16:51:50
 package postfix;

 import java.util.Stack;

 /**
*
* @author DELL 将中缀表达式转化为后缀表达式
*/ public class Expression {
private StringBuffer iExp; // 存储中缀表达式
private Stack stack;
private StringBuffer pExp; // 存储后缀表达式 public Expression(String s) {
iExp = new StringBuffer(s);
stack = new Stack();
pExp = new StringBuffer();
} public String toPostfix() throws Exception {
while (iExp.length() != 0) {
char c = iExp.charAt(0);
iExp.deleteCharAt(0);
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
pExp.append(c);
break;
case '(':
stack.push(c);
break;
case ')':
while (stack.peek() != (Object) '(') {
pExp.append(stack.pop());
}
stack.pop();
break;
case '+':
case '-':
while (!stack.isEmpty() && stack.peek() != (Object) '(') {
pExp.append(stack.pop());
}
stack.push(c); break;
case '*':
case '/':
while (!stack.isEmpty() && stack.peek() != (Object) '(' && stack.peek() != (Object) '+'
&& stack.peek() != (Object) '-') {
pExp.append(stack.pop());
}
stack.push(c);
break;
case '^':
stack.push('^');
break;
default:
System.out.println("出现错误字符"+c);
break;
} }
while (!stack.isEmpty()) {
pExp.append(stack.pop());
}
return pExp.toString();
} }

撰写时间:2017-08-13 16:50:11

修改时间: