使用逆波兰表达式完成计算
package stack;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
import java.util.stream.Collectors;
public class PolandNotation {
public static void main(String[] args) throws Exception {
//先定义逆波兰表达式
String suffixExpression = "4 5 * 8 - 60 + 8 2 / +";
String[] s = suffixExpression.split(" ");
List<String> collect = Arrays.stream(s).collect(Collectors.toList());
int res = calculator(collect);
System.out.println("计算的结果 = " + res);
}
private static int calculator(List<String> list) throws Exception {
//创建栈
Stack<String> stack = new Stack<>();
for (String item : list) {
if (item.matches("\\d+")) {
//入栈
stack.push(item);
} else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")) {
res = num1 + num2;
} else if (item.equals("-")) {
res = num1 - num2;
} else if (item.equals("*")) {
res = num1 * num2;
} else if (item.equals("/")) {
res = num1 / num2;
} else {
throw new Exception("运算错误");
}
stack.push("" + res);
}
}
return Integer.parseInt(stack.pop());
}
}
将表达式转换成中缀表达式,将中缀表达式转换成后缀表达式
package stack;
import java.util.ArrayList;
import java.util.Stack;
public class PolishDemo {
public static void main(String[] args) {
String expression = "1+((2+3)*4)-5";
//中缀表达式
ArrayList<String> list = new ArrayList<>();
int i = 0;
String str;
char c;
do {
//如果c是一个非数字,需要加入到list
if ((c = expression.charAt(i)) < 48 || (c = expression.charAt(i)) > 57) {
list.add("" + c);
i++;
} else {//如果是一个数,需要考虑多位数
str = "";
while (i < expression.length() && (c = expression.charAt(i)) >= 48 && (c = expression.charAt(i)) <= 57) {
str += c;
i++;
}
list.add(str);
}
} while (i < expression.length());
Stack<String> s1 = new Stack<>();//符号栈
ArrayList<String> s2 = new ArrayList<>();//储存中间结果的list2
for (String item : list) {
//如果是一个数,加入到s2
if (item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
//如果是右括号,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,
// 此时将这一对括号丢弃
while (!s1.peek().equals("(")) {
s2.add(s1.pop());
}
//将"("弹出栈,消除小括号
s1.pop();
} else {
//当item的优先级小于等于s1栈顶运算符,将s1栈顶的运算符弹出并加入到s2中,
// 再次与s1中新的栈顶运算符相比较
while (s1.size() != 0 && priority(s1.peek()) >= priority(item)) {
s2.add(s1.pop());
}
//当前的运算符item压入栈
s1.push(item);
}
}
//将s1中剩余的运算符依次弹出并加入到s2中
while (s1.size() != 0) {
s2.add(s1.pop());
}
//打印出后缀表达式 123+4*+5-
for (String s : s2) {
System.out.print(s);
}
}
public static int priority(String oper) {
int res = 0;
switch (oper) {
case "+":
case "-":
res = 1;
break;
case "*":
case "/":
res = 2;
break;
default:
System.out.println("不存在该运算符");
break;
}
return res;
}
}