利用栈 逆波兰表达式计算

主要思路就是把数放进栈中,如果遇见符号我们就计算,计算后数还是要放入栈,不保存符号

在这里插入代码片package a;

import java.util.Stack;

public class CalDemo {
    public static void main(String[] args) {
        String expr = "3 4 + 5 * 6 -";//(3+4)x5-6这个是源表达式。逆波兰
        String[] strs = expr.split(" ");
        System.out.println("strs = " + strs);
        int res = calculate(strs);
        System.out.println("res = " + res);

    }

    private static int calculate(String[] strs) {
        Stack<String> sta = new Stack<>();
        for (String s : strs) {
            if(s.matches("\\d+")){
                sta.push(s);

            }else {
                int n1 = Integer.parseInt(sta.pop());
                int n2 = Integer.parseInt(sta.pop());
                int res = 0;
                switch (s) {
                    case "+":res = n2+n1;
                    break;
                    case "-":res = n2-n1;
                        break;
                    case "*":res = n2*n1;
                        break;
                    case "/":res = n2/n1;
                        break;
                        default:break;
                }
                sta.push(""+res);

            }
        }
        return Integer.parseInt(sta.pop());
    }


}

发布了66 篇原创文章 · 获赞 0 · 访问量 770

猜你喜欢

转载自blog.csdn.net/Be_With_I/article/details/104197059