后缀表达式思路:
首先定义一个栈,遍历每个数据
1)遇到数字直接入栈;
2)遇到字符串就pop();两个值;
3)根据当前扫描到的运算符进行计算;
4)将结果入栈,栈内最后一个值就是结果;
public class Suffix {
public static void main(String[] args) {
// 定义一个后缀表达式
String str = "3 4 + 5 * 6 -";
List<String> list = getListString(str);
int calculate = calculate(list);
System.out.println(calculate);
}
// 获取集合
public static List<String> getListString(String str) {
List<String> list = new ArrayList<String>();
String[] split = str.split(" ");
for (String s : split) {
list.add(s);
}
return list;
}
/**
* 完成比波兰表达式算法
* 1)从左到右扫描,将3和4入栈;
* 2)遇到+运算符,因此弹出4和3(4为栈顶,3为次栈顶),计算3+4的值,得到7,再将7入栈;
* 3)将5入栈;
* 4)接下来是*运算符,因此弹出5和7,计算5*7=35,将35入栈;
* 5)将6入栈;
* 6)最后是-运算符,计算35-6=29,由此得出最后结果;
*
* @return
*/
public static int calculate(List<String> list) {
Stack<String> stack = new Stack<String>();
for (String s : list) {
if (s.equals("+") || s.equals("-") || s.equals("*") || s.equals("/")) {
int num = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0; //结果
// 根据运算符计算
if (s.equals("+")) {
res = num + num2;
} else if (s.equals("-")) {
res = num2 - num;
} else if (s.equals("*")) {
res = num * num2;
} else if (s.equals("/")) {
res = num2 / num;
}
// 把结果入栈
stack.push("" + res);
} else {
// 如果是数字直接入栈
stack.push(s);
}
}
// 最后一个数字就是结果
return Integer.parseInt(stack.pop());
}
}