前缀、中缀、后缀表达式规则及逆波兰计算器

一、前缀表达式 (波兰表达式)

        前缀表达式运算符位于操作数之前:如(3+4)*5-6 => - * + 3 4 5 6

二、中缀表达式

与数学算式运算一样:如(3+4)*5-6

三、后缀表达式(逆波兰表达式)

        与前缀表达式相似,只不过运算符位于操作数之后:如 (3+4)*5-6 => 3 4 + 5 * 6 -

逆波兰计算器(代码实现):

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

public class PolandNotation {
    public static void main(String[] args) {
        //给定表达式(中缀写法(3+4)*5-6)
        String suffixExpression = "3 4 + 5 * 6 -";
        List list =  getList(suffixExpression);
        int res= calculate(list);
        System.out.println(res);
    }
    public  static List getList(String suffixExpression){
        String[] strings = suffixExpression.split(" ");

        List list = new ArrayList();

        Collections.addAll(list, strings);

        return list;
    }

    public static int calculate(List ls){
        Stack stack = new Stack();
        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());
    }
}

你可能感兴趣的:(java)