1、源码
PolandNotation类
package com.study.stack;import java.util.ArrayList;import java.util.List;import java.util.Stack;public class PolandNotation {public static void main(String[] args) {//定义一个逆波兰表达式//(3+4)*5-6 -> 3 4 + 5 * 6 -String suffixExpression = "3 4 + 5 * 6 -";List<String> listString = getListString(suffixExpression);System.out.println(listString);int res = calculate(listString);System.out.println(res);}public static List<String> getListString(String suffixExpression){String[] s = suffixExpression.split(" ");List<String> list = new ArrayList<>();for (String arr : s) {list.add(arr);}return list;}public static int calculate(List<String> ls){Stack<String> stack = new Stack<>();for (String l : ls) {if (l.matches("\\d+")){stack.push(l);}else {int num2 = Integer.parseInt(stack.pop());int num1 = Integer.parseInt(stack.pop());int res = 0;if(l.equals("+")){res =num1+num2;}else if (l.equals("-")){res = num1-num2;}else if (l.equals("*")){res = num1*num2;}else if (l.equals("/")){res = num1/num2;}else {throw new RuntimeException("运算符有误");}stack.push(""+res);}}return Integer.parseInt(stack.pop());}}
测试结果
