java数据结构和算法——中缀转后缀表达式代码示例

一、中缀转后缀表达式思路示意图

在这里插入图片描述

二、中缀转后缀表达式代码示例

示例需求:中缀表达式:1+((2+3)×4)-5 转换成后缀表达式:1 2 3 + 4 × + 5 –

1、代码

package com.rf.springboot01.dataStructure.stack.reversePolishNotation;

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

/**
 * @description:  中缀表达式转后缀表达式
 * @author: xiaozhi
 * @create: 2020-07-29 14:24
 */
public class infixConvertorSuffix {
    public static void main(String[] args) {
       // 定义一个中缀表达式, 示例:1+((2+3)×4)-5 =>1 2 3 + 4 × + 5 –
        String expression = "1+((2+3)*4)-5";
        //中缀表达式转成list  示例:1+((2+3)×4)-5 =>[1, +, (, (, 2, +, 3, ), *, 4, ), -, 5]
        List<String> infixConvertorList = infixConvertorList(expression);
        System.out.println("中缀表达式对应的list======"+infixConvertorList);
        List<String> suffixList=infixListConvertorSuffixList(infixConvertorList);
        System.out.println("后缀表达式对应的list======"+suffixList);
        int result=computer(suffixList);
        System.out.println("中缀表达式计算的结果为:"+result);
    }

    /** 
    * @Description: 中缀表达式转list
    * @Param: String
    * @Author: xz  
    * @return: java.util.List<java.lang.String>
    * @Date: 2020/7/29 14:27  
    */ 
    public static List<String> infixConvertorList(String str){
        List<String> list=new ArrayList();
        String s;//用于多位数的拼接
        char c;// 每遍历到一个字符,就放入到c
        int i=0;
        do{
            if((c=str.charAt(i))<48 || (c=str.charAt(i))>57 ){//如果非数字
                list.add(c+"");//字节转字符串,在添加到list
                i++;
            }else{//如果是数字,考虑多位数拼接
                s="";
                while(i<str.length() && (c=str.charAt(i))>=48 && (c=str.charAt(i))<=57){
                   s+=c;
                   i++;
                }
                list.add(s);
            }
        }while(i<str.length());
        return list;
    }
    
    /** 
    * @Description:  将得到的中缀表达式对应的List => 后缀表达式对应的List
    * @Param:  
    * @Author: xz  
    * @return: 
    * @Date: 2020/7/29 15:00  
    */
    public static List<String> infixListConvertorSuffixList(List<String> ls){
        //定义一个运算符栈
        Stack<String> s1=new Stack<>();
        //定义一个储存中间结果的栈s2,由于s2栈没有pop操作,而且后面我们还需要逆序输出,
        // 因此直接使用 List<String> 代替stack<String>
        List<String> s2 = new ArrayList<String>();
        for(String item:ls){
            if(item.matches("\\d+")){//如果是数字
                s2.add(item);//入储存中间结果的栈s2
            }else if(item.equals("(")){//如果是左括号,直接入运算符栈s1
                s1.push(item);
            }else if(item.equals(")")){//如果是右括号,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
                while(!s1.peek().equals("(")){
                    s2.add(s1.pop());
                }
                s1.pop();//!!! 将左括号弹出 s1栈, 消除小括号
            }else{//当item的优先级小于等于s1栈顶运算符, 将s1栈顶的运算符弹出并加入到s2中,
                while(s1.size() != 0 && Operation.getOperationValue(item)<=Operation.getOperationValue(s1.peek())){
                    s2.add(s1.pop());
                }
                //还需要将item压入栈
                s1.push(item);
            }
        }
        //将s1中剩余的运算符依次弹出并加入s2
        while(s1.size() != 0) {
            s2.add(s1.pop());
        }

        return s2; //注意因为是存放到List, 因此按顺序输出就是对应的后缀表达式对应的List
    }

    /**
     * @Description:  完成对逆波兰表达式的运算
     *      1)从左至右扫描,将3和4压入堆栈;
     * 		2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
     * 		3)将5入栈;
     * 		4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈;
     * 		5)将6入栈;
     * 		6)最后是-运算符,计算出35-6的值,即29,由此得出最终结果
     * @Param:
     * @Author: xz
     * @return:
     * @Date: 2020/7/28 23:10
     */
    public static int computer(List<String> list){
        // 创建给栈, 只需要一个栈即可
        Stack<String> stack =new Stack<>();
        //遍历
        for(String data:list){
            if(data.matches("\\d+")){//匹配的是多位数
                stack.push(data);//入栈
            }else{//是符号,先pop出两个数,并运算,再入栈
                int num2=Integer.parseInt(stack.pop());
                int num1=Integer.parseInt(stack.pop());
                int result=0;
                if(data.equals("+")){
                    result=num1+num2;
                }else if(data.equals("-")){
                    result=num1-num2;
                }else if(data.equals("*")){
                    result=num1*num2;
                }else if(data.equals("/")){
                    result=num1/num2;
                }else{
                    throw new RuntimeException("运算符有误");
                }
                //把结果result转字符串后入栈
                stack.push(result+"");
            }
        }
        //最后留在stack中的数据是运算结果
        return  Integer.parseInt(stack.pop());
    }
}

/**
* @Description: 编写一个类 Operation, 可以返回一个运算符对应的优先级
* @Param:
* @Author: xz
* @return:
* @Date: 2020/7/29 16:06
*/
class Operation{

    private static int ADD=1;//默认加法的优先级为1
    private static int SUB=1;//默认减法的优先级为1
    private static int MUL=2;//默认乘法的优先级为2
    private static int DIV=2;//默认除法的优先级为2

    /** 
    * @Description:  获取运算符对应的优先级
    * @Param: [oper]  符号
    * @Author: xz  
    * @return: int
    * @Date: 2020/7/29 16:08  
    */ 
    public static int getOperationValue(String oper){
          int result=0;
          switch (oper){
              case "+":
                  result=ADD;
                  break;
              case "-":
                  result=SUB;
                  break;
              case "*":
                  result=MUL;
                  break;
              case "/":
                  result=DIV;
                  break;
              default:
                  System.out.println("不存在该运算符:"+oper);
                  break;
          }
          return result;
    }

}

2、运行测试类,结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小志的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值