后缀表达式 简单运算

public class MM{
   public static void main(String[] args){
        String str="3 4 + 5 * 6 - ";
        getList(str);
        List<String> rpnList=getList(str);
        System.out.println(calculate(rpnList));
    }
    public static List<String> getList(String str){
        String[] arr=str.split(" ");
        List<String> list=new ArrayList<> ();
        for(String i:arr){
            list.add(i);
        }
        return list;
    }
    public static int calculate(List<String> ls){
        //创建一个栈
        Stack<String> stack=new Stack<> ();
        //创建 ls
        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());
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个中等难度的问题,我来解释一下。 中缀表达式是我们常见的数学表达式,如 3 + 4 * 5 - 6 / 2。而后缀表达式,也叫逆波兰表达式,是一种不含括号的表达式,运算符号放在操作数的后面。例如,上述中缀表达式的后缀表达式为 3 4 5 * + 6 2 / -。 转换中缀表达式为后缀表达式需要用到栈这种数据结构。我们从左到右遍历中缀表达式的每个元素,如果是数字,就直接输出;如果是运算符,则需要判断其与栈顶运算符的优先级,如果栈顶运算符优先级高于或等于当前运算符,则将栈顶运算符弹出并输出,直到栈为空或栈顶运算符优先级低于当前运算符,最后将当前运算符入栈。 下面是一个示例代码,可以转换一个字符串表示的中缀表达式为后缀表达式: ```python def infix_to_postfix(expr): precedence = {'+': 1, '-': 1, '*': 2, '/': 2, '^': 3} stack = [] postfix = [] for c in expr: if c.isdigit(): postfix.append(c) elif c in precedence: while stack and stack[-1] in precedence and precedence[c] <= precedence[stack[-1]]: postfix.append(stack.pop()) stack.append(c) elif c == '(': stack.append(c) elif c == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() while stack: postfix.append(stack.pop()) return ' '.join(postfix) ``` 你可以将中缀表达式作为参数传递给这个函数,它会返回表示后缀表达式的字符串。例如: ```python expr = '3 + 4 * 5 - 6 / 2' postfix = infix_to_postfix(expr) print(postfix) # 输出:3 4 5 * + 6 2 / - ``` 希望这个代码对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值