package Stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author 郑道炫
* @version 1.0
*/
public class PolandNotation {
public static void main(String[] args) {
//定义给逆波兰表达式
//(3+4)*5-6 = > 3 4 + 5* 6
//说明为了方便,逆波兰表达式的数字和符号使用空格隔开
String suffixExpression = "3 4 + 5 * 6 -";
//思路
//1.先将“3 4 + 5 * 6 - ”=>放到ArrayList中
//2.将ArrayList传递给一个方法,遍历Arraylist配合栈完成计算
List<String> listString = getListString(suffixExpression);
for (String s : listString) {
System.out.print(s);
}
int res = calculate(listString);
System.out.println(" ");
System.out.println("计算结果是:"+res);
}
//将一个逆波兰表达式,依次将数据和运算符放入到ArrayList中
public static List<String> getListString(String suffixExpression) {
//将suffixExpression分割
String[] split = suffixExpression.split(" ");
List<String> lists = new ArrayList<>();
for (String string : split) {
lists.add(string);
}
return lists;
}
//1.从左到右进行扫描,将3和4放入堆栈
//2.遇到+运算符,因此弹出4和3,计算出3+4的值,得7,再将7入栈,
//3.将5入栈
//4.接下来是x运算符,因此弹出5和7,计算出7*5=35,将35入栈;
//5.将6入栈,
//6.最后是-运算符,计算出35-6的值,即29,由此得出最终结果
//
//
public static int calculate(List<String> ls) {
//创建栈,只需要一个栈即可
Stack<String> stack = new Stack<>();
//遍历 ls
for (String item : ls) {
//使用正则表达式取出式
if (item.matches("\\d+")) {
//入栈
stack.push(item);
} else {
//pop出两个数,并运算,再入栈
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
switch (item) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "/":
res = num1 / num2;
break;
case "*":
res = num1 * num2;
break;
default:
throw new RuntimeException("运算符有误");
}
//把res入栈
stack.push(res+"");
}
}
//最后留在stack中的数据时运算结果
return Integer.parseInt( stack.pop());
}
}
(3+4)*5-6
计算结果是:29