• 前后缀表达式


    前缀表达式

    image-20200526120940217

    后缀表达式(逆波兰)

    image-20200527092630977

    public class PolandNotation {
        public static void main(String[] args) {
            String suffixExpression = "3 4 + 5 * 6 -";
            List<String> list = getListString(suffixExpression);
            int res = calculate(list);
            System.out.println("计算的结果是:"+ res);
        }
        //将表达式转换成ArrayList
        public static List<String> getListString(String suffixExpression){
            String[] s = suffixExpression.split(" ");
            List list = new ArrayList();
            for (String l : s){
                list.add(l);
            }
            return list;
        }
        //进行逆波兰计算
        public static int calculate(List<String> ls){
            Stack<String> stack =new Stack<String>();
            for (String item : ls){
                if (item.matches("\d+")){
                    stack.push(item);
                }else {
                    int num1 = Integer.parseInt(stack.pop());
                    int num2 = Integer.parseInt(stack.pop());
                    int res = 0;
                    if (item.equals("+")){
                        res = num1 + num2;
                    } else if (item.equals("-")){
                        res = num2 - num1;
                    }else if (item.equals("*")){
                        res = num2 * num1;
                    }else if (item.equals("/")){
                        res = num2 / num1;
                    }else {
                        throw new RuntimeException("运算符有误");
                    }
                    stack.push(res + "");
                }
            }
            return Integer.parseInt(stack.pop());
        }
    }
    
    

  • 相关阅读:
    Create方法失效而没有提示错误信息
    JS弹出窗口控制
    本周活动
    JavaScript的初步了解
    关于PHP接收文件的资料
    mvc模式改进网站结构
    一周动态
    排序
    Java的内存泄漏
    Android笔记
  • 原文地址:https://www.cnblogs.com/chaostudy/p/12971811.html
Copyright © 2020-2023  润新知