一个表达式E的后缀形式可以如下定义:
(1)如果E是一个变量或常量,则E的后缀式是E本身。(2)如果E是E1 op E2形式的表达式,这里op是如何二元操作符,则E的后缀式为E1'E2' op,这里E1'和E2'分别为E1和E2的后缀式。
(3)如果E是(E1)形式的表达式,则E1的后缀式就是E的后缀式。
如:我们平时写a+b,这是中缀表达式,写成后缀表达式就是:ab+
(a+b)*c-(a+b)/e的后缀表达式为:
(a+b)*c-(a+b)/e
→((a+b)*c)((a+b)/e)-
→((a+b)c*)((a+b)e/)-
→(ab+c*)(ab+e/)-
→ab+c*ab+e/-
public class AlgTest {
private static Stack<Integer> stack = new Stack<Integer>();public static void main(String[] args) {
String[] tokens = new String[] { "2", "1", "+", "3", "*" };
String[] tokens1 = new String[]{"4", "13", "5", "/", "+"};
Integer value = polish(tokens1);
System.out.println(value);
}
public static Integer polish(String[] tokens) {
String operators = "+-*/";
for (String s : tokens) {
if (!operators.contains(s)) {
stack.push(Integer.valueOf(s));
} else {
Integer a = stack.pop();
Integer b = stack.pop();
switch (s) {
case "+":
stack.push(b + a);
break;
case "-":
stack.push(b - a);
break;
case "*":
stack.push(b * a);
break;
case "/":
stack.push(b / a);
break;
}
}
}
return stack.pop();
}
}