逆波兰计算器-栈

java.util.Stack;

/**

  • @PROJECT_NAME: DataStruct

  • @DESCRIPTION:

  • @USER: 28416

  • @DATE: 2022/11/30 14:41

  • 逆波兰表达式
    */
    public class PolandNotation {
    public static void main(String[] args) {
    //先定义一个逆波兰表达式
    String suffixExpression = "3 4 + 5 * 6 -";
    //思路
    //1.先将 3 4 + 5 * 6 - 放入到arraylist中
    //将arraylist 传递一个方法,遍历 配合栈 完成计算
    List prnList = getListString(suffixExpression);
    System.out.println("prnList"+prnList);

     int res = calculate(prnList);
     System.out.println(res);
    

    }
    //将一个逆波兰表达式依次将数据和运算符 放入到ArrayList中
    public static List getListString(String suffixExpression){
    //将 suffixExpression 分割
    String[] split = suffixExpression.split(" ");
    List list = new ArrayList();
    for (String ele : split) {
    list.add(ele);
    }
    return list;
    }
    //完成对逆波兰表达式的计算
    public static int calculate(List ls){
    //创建栈,只需要一个栈即可
    Stack stack = new Stack();
    //遍历 ls
    for (String item : ls) {
    //正则表达式
    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 RuntimeException("运算符有误");
    }
    stack.push(""+res);
    }
    }
    return Integer.parseInt(stack.pop());
    }

}

posted @ 2022-11-30 23:34  wiselee/  阅读(28)  评论(0编辑  收藏  举报