首页 > 其他 > 详细

前后缀表达式

时间:2020-05-27 12:55:36      阅读:41      评论:0      收藏:0      [点我收藏+]

前缀表达式

技术分享图片

后缀表达式(逆波兰)

技术分享图片

技术分享图片

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());
    }
}

前后缀表达式

原文:https://www.cnblogs.com/chaostudy/p/12971811.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!