中缀转后缀计算

中缀表达式(10+20/2*3)/2+8,其转换成后缀表达式则为10 20 2 / 3 * + 2 / 8 +

转换过程需要用到栈,具体过程如下:

1)当遇到操作数,我们就直接将其输出。

2)当遇到操作符,则我们将其放入到栈中,遇到左括号时我们也将其放入栈中。

3)当遇到一个右括号,则将栈元素弹出,将弹出的操作符输出直到遇到左括号为止。
注意,左括号只弹出并不输出。

package Stack;
import ListInterfcae_list.ArrayList;
/*
中缀转后缀
 */
public class InfixToSuffix {
    public static void main(String[] args){
        String infixExpression = "(10+20/2*3)/2+8";
        String suffixExpression = infixToSuffix(infixExpression);
        System.out.println(suffixExpression);
    }

    public static String infixToSuffix(String infixExpression) {
        ArrayStack<String> opStack = new ArrayStack<String>();
        ArrayList<String> suffixList = new ArrayList<>();
        infixExpression = insertBlanks(infixExpression);
        String[] tokens = infixExpression.split(" ");
        for (String token : tokens) {
            //过滤空串
            if (token.length() == 0) {
                continue;
            }
            //如果是操作符
            if (isOperator(token) ) {
                while (true){
                    if (opStack.isEmpty() || opStack.peek().equals("(") || priority(opStack.peek()) < priority(token)) {
                        opStack.push(token);
                        break;
                    }
                    suffixList.add(opStack.pop());
                }
            }else if (token.equals("(")){
                opStack.push(token);
            }else if (token.equals(")")){
                while (!opStack.peek().equals("(")) {
                    suffixList.add(opStack.pop());
                }
                opStack.pop();
            }else if (isNumber(token)){
                suffixList.add(token);
            }else {
                throw new IllegalArgumentException("wrong char :" + infixExpression);
            }
            }
            while (!opStack.isEmpty()){
                suffixList.add(opStack.pop());
            }
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < suffixList.size(); i++) {
            sb.append(suffixList.get(i));
            sb.append(' ');
        }
        return sb.toString();
}

    private static boolean isNumber(String token) {
        return token.matches("\\d+");
    }
    private static int priority(String token) {
        if (token.equals("+") || token.equals("-")) {
            return 0;
        }
        if (token.equals("*") || token.equals("/")) {
            return 1;
        }
        return -1;
    }
    private static boolean isOperator(String token) {
        return token.equals("+") || token.equals("-") || token.equals("*") ||token.equals("/");
    }
    private static String insertBlanks(String infixExpression) {
        StringBuilder sb = new StringBuilder();
        char c ;
        for (int i = 0; i < infixExpression.length(); i++) {
            c = infixExpression.charAt(i);
            if (c == '(' || c == ')' || c == '+' || c == '-' || c == '*'
                    || c == '/'){
                sb.append(" ");
                sb.append(c);
                sb.append(" ");
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

后缀计算器:

对于后缀表达式,我们只需要一个栈即可,当遇到数字时直接进栈,当遇到操作符时直接弹栈两个数字进行运算,再将结果进栈

package Stack;

public class SuffixCalculator {
    public static void main(String[] args) {
        String infixExpression = "(10+20/2*3)/2+8";
        String expression = InfixToSuffix.infixToSuffix(infixExpression);
        System.out.println(expression);
        ArrayStack<Integer> stack = new ArrayStack<Integer>();
        String[] tokens = expression.split(" ");
        for (String token :tokens){
            //如果是数字直接进栈
            if (isNumber(token)){
                stack.push(new Integer(token));
            }
            if (isOperator(token)){
                processionExpression(stack,token);
            }
        }
        System.out.println(stack.pop());

    }

    private static boolean isOperator(String token) {
        return token.equals("+") || token.equals("-") || token.equals("*") ||token.equals("/");

    }

    private static boolean isNumber(String token) {
        return token.matches("\\d+");  // \\d+  表示匹配的是多个数字
    }


    private static void processionExpression(ArrayStack<Integer> stack, String token) {
        int num1 = stack.pop();
        int num2 = stack.pop();
        switch (token) {
            case "+":
                stack.push(num2 + num1);
                break;
            case "-":
                stack.push(num2 - num1);
                break;
            case "*":
                stack.push(num2 * num1);
                break;
            case "/":
                stack.push(num2 / num1);
                break;
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
前缀、中缀后缀表达式是数学中常用的三种表示方式。它们在计算机中的应用主要是为了方便计算机进行表达式的求值。 1. 前缀表达式(也称为波兰表达式):运算符位于操作数之前。例如,前缀表达式"+ 2 3"表示的是2+3。 2. 中缀表达式:运算符位于操作数之间。例如,中缀表达式"2 + 3"表示的是2+3。 3. 后缀表达式(也称为逆波兰表达式):运算符位于操作数之后。例如,后缀表达式"2 3 +"表示的是2+3。 计算前缀、中缀后缀表达式的方法略有不同: - 前缀表达式的计算方法: 1. 从右到左扫描表达式。 2. 遇到数字时,将其压入中。 3. 遇到运算符时,从中弹出两个数字进行运算,并将结果压入中。 4. 重复上述步骤,直到表达式结束,中的数字即为表达式的结果。 - 后缀表达式的计算方法: 1. 从左到右扫描表达式。 2. 遇到数字时,将其压入中。 3. 遇到运算符时,从中弹出两个数字进行运算,并将结果压入中。 4. 重复上述步骤,直到表达式结束,中的数字即为表达式的结果。 - 中缀表达式的计算方法: 1. 将中缀表达式换为后缀表达式。 2. 使用后缀表达式的计算方法计算结果。 下面是一个示例,演示了如何计算前缀、中缀后缀表达式: 前缀表达式计算: ```python stack = [] expression = "+ 2 3" tokens = expression.split() for token in reversed(tokens): if token.isdigit(): stack.append(int(token)) else: operand1 = stack.pop() operand2 = stack.pop() if token == '+': stack.append(operand1 + operand2) elif token == '-': stack.append(operand1 - operand2) elif token == '*': stack.append(operand1 * operand2) elif token == '/': stack.append(operand1 / operand2) result = stack.pop() print("Result:", result) # 输出:5 ``` 后缀表达式计算: ```python stack = [] expression = "2 3 +" tokens = expression.split() for token in tokens: if token.isdigit(): stack.append(int(token)) else: operand2 = stack.pop() operand1 = stack.pop() if token == '+': stack.append(operand1 + operand2) elif token == '-': stack.append(operand1 - operand2) elif token == '*': stack.append(operand1 * operand2) elif token == '/': stack.append(operand1 / operand2) result = stack.pop() print("Result:", result) # 输出:5 ``` 中缀表达式后缀表达式: ```python def infix_to_postfix(expression): precedence = {'+': 1, '-': 1, '*': 2, '/': 2} stack = [] postfix = [] tokens = expression.split() for token in tokens: if token.isdigit(): postfix.append(token) elif token == '(': stack.append(token) elif token == ')': while stack and stack[-1] != '(': postfix.append(stack.pop()) stack.pop() # 弹出左括号 else: while stack and stack[-1] != '(' and precedence[token] <= precedence.get(stack[-1], 0): postfix.append(stack.pop()) stack.append(token) while stack: postfix.append(stack.pop()) return ' '.join(postfix) expression = "2 + 3 * 4" postfix_expression = infix_to_postfix(expression) print("Postfix expression:", postfix_expression) # 输出:2 3 4 * + # 使用后缀表达式的计算方法计算结果 stack = [] tokens = postfix_expression.split() for token in tokens: if token.isdigit(): stack.append(int(token)) else: operand2 = stack.pop() operand1 = stack.pop() if token == '+': stack.append(operand1 + operand2) elif token == '-': stack.append(operand1 - operand2) elif token == '*': stack.append(operand1 * operand2) elif token == '/': stack.append(operand1 / operand2) result = stack.pop() print("Result:", result) # 输出:14 ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小张不会打篮球

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

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

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

打赏作者

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

抵扣说明:

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

余额充值