数据结构 04 - 逆波兰表达式实现 && 中缀转后缀表达式

一、逆波兰表达式实现(后缀表达式)

1.定义:运算符位于操作数之后,例如:3 + 4 * 5 - 6,则写成3 4 + 5 * 6 -

2.思路分析

(1).先定义个逆波兰表达式:3 4 + 5 * 6 -
(2).先将"3 4 + 5 * 6 -"放到ArrayList配合栈完成计算
(3).将ArrayList传递给一个方法,遍历ArrayList,遍历ArrayList配合栈完成计算

代码实现:

public class PolandNotation {
    public static void main(String[] args) {
        String suffixExpression = "3 4 + 5 * 6 -";
        List<String> list = getlistString(suffixExpression);
        int res = calculate((list));
        System.out.println("计算结果是:" + res);
    }

    //1.将一个逆波兰表达式,依次将数据和运算符放到ArrayList中
    public static List<String> getlistString(String suffffixExpression){
        //将suffixExpression分割
        String[] split = suffffixExpression.split(" ");
        List<String> list = new ArrayList<String>();
        for (String ele : split) {
            list.add(ele);
        }
        return list;
    }

    //2.完成对逆波兰表达式的运算
    public static int calculate(List<String> ls){
        //创建给栈,只需要一个栈即可
        Stack<String> stack = new Stack<String>();
        //遍历ls
        for (String item : ls) {
            //这里使用正则表示来取出数
            if(item.matches("\\d+")){//匹配的是多位数
                //入栈
                stack.push(item);
            }else {
                int num2 = Integer.parseInt(stack.pop());//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 + "");//要把最后结果入栈,res+""可以把数转化为字符串
            }
        }
        return Integer.parseInt(stack.pop());
    }
}

二、中缀转后缀表达式

1.思路分析
在这里插入图片描述
2.准备步骤:
(1).初始化两个栈:运算符栈s1和储存中间结果的栈s2
(2).从左到右扫描中缀表达式,即将其遍历

3.遇到的情况有以下三种:
(1).遇到数值时,将其压入s2
(2).遇到运算符时,比较其与s1栈顶运算符的优先级
(2.1)如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈
(2.2)否则,若优先级比栈顶运算符优先级高,也将运算符压入s2
(2.3)否则,将s1栈顶的运算符弹出并压入到s2中,再次转到4.1与s1中新的栈顶运算符比较

3.遇到括号时

(1)如果为左括号“(”,则直接压入s1
(2)如果为右括号“)”,则一次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃

4.后续步骤:

(1).重复前面的步骤,直到遍历完整个表达式
(2).将s1剩余的运算符依次弹出并压入s2
(3).依次弹出s2中的元素并输出,其结果的逆序就是该中缀表达式对应的后缀表达式

代码实现:

//完成将一个中缀表达式转换成后缀表达式
//1.1+((2+3)*4)-5转成123+4*+5-
//2.因为直接对str进行操作不方便,因此先将中缀表达式放入对应的list
//即:1+((2+3)*4)-5  -->  ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]
//3.将得到的中缀表达式对应的list转成后缀表达式对应的list
//即:ArrayList[1,+,(,(,2,+,3,),*,4,),-,5]  -->  ArrayList[1,2,3,+,4,*,+,5,-]

public class Notation {
    public static void main(String[] args){
        String expression = "1+((2+3)*4)-5";
        List<String> list = ToInfixExpression(expression);
        List<String> ls = PolandNotation(list);
        System.out.println(list);
        System.out.println(ls);
    }

    //1.把字符串表达式放进List
    public static List<String> ToInfixExpression(String s){
        List<String> list = new ArrayList<String>();
        String str;
        char c;
        int i = 0;
        while (i < s.length()){
            //不是数字就加进list,因为是数字还要判断是几位数
            if((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57){
                list.add(c + "");
                i++;
            }else {
                str = "";
                while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57){
                    str += c;
                    i++;
                }
                list.add(str);
            }
        }
        return list;
    }

    //2.将得到的中缀表达式对应的list转成后缀表达式对应的list
    public static List<String> ToPolandNotation(List<String> ls){
        //先确定两个栈
        Stack<String> s1 = new Stack<>();
        List<String> s2 = new ArrayList<String>();

        //遍历输入的ls,分三种情况处理,当遍历的为数字、括号和运算符时,进行相应的处理
        for (String item : ls) {
            // 如果是一个数就入s2
            if (item.matches("\\d+")) {
                s2.add(item);
            } else if (item.equals("(")) {
                s1.push(item);
            } else if (item.equals(")")) {
                // 如果是右括号“)",则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
                while (!s1.peek().equals("(")) {
                    s2.add(s1.pop());
                }
                s1.pop();// !!!将(弹出s1栈,消除小括号
            } else {
                // 当item的优先级小于等于栈顶运算符的优先级
                // 将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较
                // 缺少一个比较优先级的方法
                while (s1.size() != 0 && priority.getvalue(s1.peek()) >= priority.getvalue(item)) {
                    s2.add(s1.pop());
                }
                // 还需要item压入栈中
                s1.push(item);
            }
        }
        // 将s1中剩余的运算符加入到s2中
        while (s1.size() != 0) {
            s2.add(s1.pop());
        }
        return s2;// 因为是存放到List中因此正常输出就是后缀表达式
    }
}

class priority{
    public static int ADD = 1;
    public static int SUB = 1;
    public static int MUL = 2;
    public static int DIV = 2;

    public static int getvalue(String s){
        int result = 0;
        switch (s){
            case "+":
                result = ADD;
                break;
            case "-":
                result = SUB;
                break;
            case "*":
                result = MUL;
                break;
            case "/":
                result = DIV;
                break;
            default:
                System.out.println("不存在该运算符");
                break;
        }
        return result;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值