离上次写已经过了很久的时间了,现在来把这个坑填完吧
将中缀表达式变为后缀表达式的示意图如下
输入 | 输出 | 栈(顶在右) |
A+B*C+(D+E)*F | 空 | 空 |
+B*C+(D+E)*F | A | 空 |
B*C+(D+E)*F | A | + |
*C+(D+E)*F | A | + |
C+(D+E)*F | AB | +* |
+(D+E)*F | ABC | +* |
(D+E)*F | ABC*+ | + |
D+E)*F | ABC*+ | +( |
+E)*F | ABC*+D | +(+ |
E)*F | ABC*+D | +(+ |
)*F | ABC*+DE | + |
*F | ABC*+DE+ | +* |
F | ABC*+DE+ | +* |
空 | ABC*+DE+F | 空 |
空 | ABC*+DE+F*+ | 空 |
其步骤如下
(1)检查输入的下一个元素
(2)若它是一个操作数,则输出它
(3)若它是一个开括号,把它压入栈
(4)若它是一个操作符,则有如下情况
1若栈顶是一个开括号,把操作符压入栈
2若它比栈顶操作符有更高优先权,则把操作符压入栈
3否则,从栈弹出操作符到输出,并重复步骤(4)
(5)若它是一个闭括号,则弹出操作符到输出,直到遇到上一个开括号。弹出并废此开括号
(6)若还有输入,回到步骤(1)
(7)若没有输入,则弹出所有剩余操作符到输出
代码
public class InToPost {
private StackX theStack;
private String input;
private String output = "";
public InToPost(String in) {
input = in;
int stackSize = input.length();
theStack = new StackX(stackSize);
}
public String doTrans() {
for (int j = 0; j < input.length(); j++) {
char ch = input.charAt(j);
switch (ch) {
case '+':
case '-':
gotOper("" + ch, 1);
break;
case '*':
case '/':
gotOper("" + ch, 2);
break;
case '(':
theStack.push("" + ch);
break;
case ')':
gotParen(ch);
break;
default:
output = output + ch;
break;
}
}
while (!theStack.isEmpty()) {
output = output + theStack.pop();
}
return output;
}
public void gotOper(String opThis, int prec1) {
while (!theStack.isEmpty()) {
String opTop = theStack.pop();
if (opTop.contains("(")) {
theStack.push(opTop);
break;
} else {
int prec2;
if (opTop.contains("+") || opTop.contains("-"))
prec2 = 1;
else
prec2 = 2;
if (prec2 < prec1) {
theStack.push(opTop);
break;
} else
output = output + opTop;
}
}
theStack.push(opThis);
}
public void gotParen(char ch) {
while (!theStack.isEmpty()) {
String chx = theStack.pop();
if (chx.contains("("))
break;
else
output = output + chx;
}
}
}
最后附上自己做的一个计算器