Java calculation of reverse Polish notation (postfix notation) based

 


import java.util.Stack;

/**
 * @Author Snail
 * @Describe 逆波兰表达式(后缀表达式)
 * 计算包含数字和运算符的:
 *  如果是数字,则入栈
 *  如果是运算符,则弹出栈中两个元素使用运算符运算,再将结果入栈
 *  当栈中仅有一个元素时,即为结果
 * @CreateTime 2019/8/21
 */
public class ReversePolishNotation {
    public static void main(String[] args) {
        String[] notation=new String[]{"2","1","+","3","*"};
        String[] notation1=new String[]{"4","13","5","/","+"};
        Integer rpn = getRPN(notation1);
        System.out.println(rpn);
    }
    public static Integer getRPN(String[] notation){
        Stack<Integer> stack=new Stack<>();
        int a,b;
        for (int i = 0; i < notation.length; i++) {
            if (notation[i].equals("+")) {
                b = stack.pop();//注意栈是先进后出
                a = stack.pop();
                stack.push(a + b);
            } else if (notation[i].equals("-")) {
                b = stack.pop();
                a = stack.pop();
                stack.push(a - b);
            } else if (notation[i].equals("*")) {
                b = stack.pop();
                a = stack.pop();
                stack.push(a * b);
            } else if (notation[i].equals("/")) {
                b = stack.pop();
                a = stack.pop();
                stack.push(a / b);
            } else {
                int num = Integer.parseInt(notation[i]);
                stack.push(num);
            }
        }
        return stack.pop();
    }

}

stack class inherits class Vector, Vector implements List interface, List inherits the Collection interface

Published 91 original articles · won praise 54 · views 10000 +

Guess you like

Origin blog.csdn.net/BigBug_500/article/details/99949602