中缀表达式转换为后缀表达式

具体步骤:
在这里插入图片描述
*举例:1+((3+2)4)-5=》1 3 2 + 4 * + 5 -
在这里插入图片描述
代码:

public static  void main(String[] args){
        Scanner scanner=new Scanner(System.in);
            String expression="1+((3+2)*4)-5";//=>1, 3, 2, +, 4, *, +, 5, -
        List<String> list;
        list =expressionList(expression);
        System.out.println(list);
        System.out.println(calculate(list));
    }
    public static int operation(String oper){
        switch (oper){
            case "+":
                return 0;
            case "-":
                return 0;
            case "*":
                return 1;
            case "/":
                return 1;
            default:
                System.out.println("输入的字符有误");
                return -1;
        }
    }
    public static List<String> calculate(List<String> list){
        Stack<String> stack=new Stack<>();
        List<String> list1=new ArrayList<>();
        for (String item:list ) {
            if(item.matches("\\d+")){  //正则表达式 表示多位数字
                list1.add(item);
            }else if(item.equals("(")){
                stack.push(item);
            }else if(item.equals(")")){
                while(!stack.peek().equals("(")&&!stack.isEmpty()){
                    list1.add(stack.pop());
                }
                stack.pop();
            }else {
                if(stack.isEmpty()|| stack.peek().equals("(")){
                    stack.push(item);
                }else if(operation(item)>operation(stack.peek())) {
                    stack.push(item);
                } else{
                    while(!stack.isEmpty()&&operation(item)<=operation(stack.peek())){
                        list1.add(stack.pop());
                    }
                    stack.push(item);
                }
            }
        }
        while(!stack.isEmpty()) {
            list1.add(stack.pop());
        }
        return list1;
    }
    //转为list
    public static List<String> expressionList(String expression){
        List<String> list=new ArrayList<>();
        //int i=0;
        char c;
        String str="";//用于拼接多位数
        for (int i= 0; i<expression.length() ; ) {
            if((c=expression.charAt(i))>57||(c=expression.charAt(i))<48){
                list.add(c+"");
                i++;
            }else {
                str="";
                while(i<expression.length()&&(c = expression.charAt(i)) <= 57 && (c = expression.charAt(i)) >= 48){
                    str=str+c;
                    i++;
                }
                list.add(str);
            }
        }
        return list;
    }

效果图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值