利用栈实现表达式的计算。括号匹配。
中缀表达式转换为后缀表达式。
逆波兰表达式的计算
package com.yc.algorithm.stack;
import java.util.Scanner;
import java.util.Stack;
/**
* 逆波兰表达式计算
* ( 1 - 2 ) * ( 4 + 5 ) --> -9
*/
public class RPN {
public static void main(String[] args) throws Exception {
String str = change();
System.out.println("中缀表达式转后缀表达式 : " + str);
rpn(str);
}
/**
* 逆波兰表达式
* 1 2 - 4 5 + * # --> -9
* @throws Exception
*/
private static void rpn(String string) throws Exception {
Stack stack = new Stack();
double d1;
double d2;
String[] strs = string.split(" ");
for (String str : strs) {
if (str.equals("+") || str.equals("-") || str.equals("*") || str.equals("/")) {
switch (str) {
case "+":
d1 = (double)stack.pop();
d2 = (double)stack.pop();
stack.push(d1 + d2);
break;
case "-":
d1 = (double)stack.pop();
d2 = (double)stack.pop();
stack.push(d2 - d1);
break;
case "*":
d1 = (double)stack.pop();
d2 = (double)stack.pop();
stack.push(d2 * d1);
break;
case "/":
d1 = (double)stack.pop();
d2 = (double)stack.pop();
if (d1 == 0) {
throw new Exception("除零错");
}
stack.push(d2 / d1);
break;
}
} else {
stack.push(Double.parseDouble(str));
}
}
System.out.println("表达式的最终结果是 : " + stack.pop());
}
/**
* 中缀表达式转后缀表达式
* 1 - 2 ) * ( 4 + 5 ) -> 1 2 - 4 5 + * #
*/
private static String change() {
StringBuffer strbuf = new StringBuffer();
Stack stack = new Stack();
Scanner scanner = new Scanner(System.in);
String c = scanner.next();
while (!"#".equals(c)) {
if (")".equals(c)) {
String sc = (String) stack.pop();
while (!sc.equals("(")) {
strbuf.append(sc);
strbuf.append(" ");
sc = (String) stack.pop();
}
} else if ("+".equals(c) || "-".equals(c)) {
if (stack.empty()) {
stack.push(c);
} else {
String sc;
do {
sc = (String) stack.pop();
if ("(".equals(sc)) {
stack.push(sc);
} else {
strbuf.append(sc);
strbuf.append(" ");
}
} while (!stack.empty() && !sc.equals("("));
stack.push(c);
}
} else if ("*".equals(c) || "/".equals(c) || "(".equals(c)) {
stack.push(c);
} else {
strbuf.append(c);
strbuf.append(" ");
}
c = scanner.next();
}
while (!stack.empty()) {
strbuf.append(stack.pop());
strbuf.append(" ");
}
return strbuf.toString();
}
}

409

被折叠的 条评论
为什么被折叠?



