对于计算机来讲,通常后缀表达式更容易计算,因为它不用考虑优先规则和括号。表达式中的数值和操作符的顺序就足以确定计算结果。所以,程序设计语言编译器和运行时环境在其内部计算中往往使用后缀表达式。
可以借助栈将输入的中缀表达式转为后缀表达式。
中缀转后缀的思路如下:
1)如果遇到操作数,我们就直接将其输出。
2)如果遇到操作符,则我们将其放入到栈中,遇到左括号时我们也将其放入栈中。
3)如果遇到一个右括号,则将栈元素弹出,将弹出的操作符输出直到遇到左括号为止。注意,左括号只弹出并不输出。
4)如果遇到任何其他的操作符,如(“+”, “*”,“(”)等,从栈中弹出元素直到遇到发现更低优先级的元素(或者栈为空)为止。弹 出完这些元素后,才将遇到的操作符压入到栈中。有一点需要注意,只有在遇到" ) "的情况下我们才弹出" ( ",其他情况我们都不会弹出" ( "。
5)如果我们读到了输入的末尾,则将栈中所有元素依次弹出。
用Java实现类 InfixToPostfix.java
public class InfixToPostfix {
private Stack<String> stack;
public InfixToPostfix() {
stack = new Stack<String>();
}
public String changeInfixToPostfix(String infix) throws Exception {
StringBuffer postfix = new StringBuffer();
Scanner parser = new Scanner(infix);
while(parser.hasNext()) {
String item = parser.next();
if (isNumber(item)) {
//数字直接 入到 postfix
postfix.append(item).append(" ");
continue;
}
//如果是"("直接入栈
if (item.equals("(")) {
stack.push(item);
continue;
}
//如果是")"则弹出栈中元素,直到"("结束
if (item.equals(")")) {
boolean flag = false;
while (!stack.isEmpty()) {
String top = stack.peek();
//遇到左括号 结束
if (top.equals("(")) {
stack.pop();
flag = true;
break;
}
postfix.append(stack.pop()).append(" ");
}
if (!flag) {
parser.close();
throw new Exception("this infix maybe error, reason : lack '('");
}
continue;
}
// item 为普通操作符+,-,*,/
while (!stack.isEmpty()) {
String top = stack.peek();
//优先级比较
if (!isLower(top,item)) {
if (top.equals("(")) {
stack.push(item);
break;
}
postfix.append(stack.pop()).append(" ");
continue;
}
stack.push(item);
break;//结束,获取下一个操作数
}
if (stack.isEmpty()) {
stack.push(item);
}
}
//把栈里的弹出
while(!stack.isEmpty()) {
postfix.append(stack.pop()).append(" ");
}
parser.close();
return postfix.toString();
}
/**
* Description: 比较栈顶元素和输入的优先级<br>
*
* @author liu.mingqing<br>
* @taskId <br>
* @param top
* @param item
* @return <br>
*/
private boolean isLower(String top, String item) {
return ((item.equals("*") || item.equals("/"))&&(top.equals("+") || top.equals("-")));
}
/**
* Description: <br>
*
* @author liu.mingqing<br>
* @taskId <br>
* @param item
* @return <br>
*/
private boolean isNumber(String item) {
return item.matches("[0-9]+");
}
public static void main(String[] args) throws Exception {
String infix = "( 3 * 4 - ( 2 + 5 ) ) * 4 / 2";
InfixToPostfix iToP = new InfixToPostfix();
System.out.println(iToP.changeInfixToPostfix(infix));
}
}
测试结果:
3 4 * 2 5 + - 4 * 2 /