java 中缀表达式求值

中缀表达式求值:

遍历表达式

1、如果是数字,直接入数栈

2、如果是符号:

(1)如果符号栈为空,直接入栈。

(2)如果符号栈不为空:

         1)如果当前运算符的优先级小于等于符号栈中的操作符,需要从数栈中pop出两个数字,在符号栈中pop出一个符号,进行运算,将运算 结果压入数栈,并将当前操作符压入符号栈。

         2)如果当前操作符优先级大于栈中操作符,直接入符号栈。

3、扫描完毕,顺序的从数栈和符号栈中pop相应的数字和符号进行计算,并将运算结果压入数栈。

4、最后数栈中只有一个数字,便是表达式的运算结果。

public class CalculatorStack {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public CalculatorStack(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[maxSize];
    }

    // 栈是否为空
    public boolean isEmpty() {
        return top == -1;
    }
    // 栈是否满
    public boolean isFull() {
        return top == (maxSize - 1);
    }

    // 入栈
    public void push(int n) {
        if (isFull()) {
            throw new RuntimeException("栈已满");
        }
        stack[++top] = n;
    }

    // 出栈
    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        return stack[top--];
    }

    // 返回运算符的优先级,使用数字表示,数字越大,优先级越高
    public int priority(int op) {
        if (op == '*' || op == '/') {
            return 1;
        }
        if (op == '+' || op == '-') {
            return 0;
        }
        else
            return  -1;
    }
    // 判断是不是运算符
    public boolean isOp(char val) {
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    // 查看栈顶元素
    public int getTopValue() {
        return stack[top];
    }

    // 计算
    public int cal(int num1, int num2, int op) {
        return switch (op) {
            case '+' -> num1 + num2;
            case '-' -> num2 - num1;
            case '*' -> num1 * num2;
            case '/' -> num2 / num1;
            default -> 0;
        };
    }
}


public static void main(String[] args) {
        String expression = "7*2*2-5+1-5+3-4";
        CalculatorStack numStack = new CalculatorStack(10);
        CalculatorStack opStack = new CalculatorStack(10);

        int num1 = 0;
        int num2 = 0;
        int op = 0;
        int index = 0;
        char ch = ' ';
        String tmp = "";
        while (index < expression.length()) {
            ch = expression.substring(index, index + 1).charAt(0);
            if (opStack.isOp(ch)) {
                if (!opStack.isEmpty()) {
                    if (opStack.priority(ch) <= opStack.priority(opStack.getTopValue())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        op = opStack.pop();
                        numStack.push(numStack.cal(num1, num2, op));
                    }
                }
                opStack.push(ch);
            } else {
                // 多位数处理
                tmp += ch;
                if (index == (expression.length() - 1)) {
                    numStack.push(Integer.parseInt(tmp));
                } else {
                    if (opStack.isOp(expression.substring(index + 1, index + 2).charAt(0))) {
                        numStack.push(Integer.parseInt(tmp));
                        tmp = "";
                    }
                }
            }
            index++;
        }
        while (!opStack.isEmpty()) {
            num1 = numStack.pop();
            num2 = numStack.pop();
            op = opStack.pop();
            numStack.push(numStack.cal(num1, num2, op));
        }
        System.out.println(expression + '=' + numStack.pop());
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Java中缀表达式求值的示例代码: ```java import java.util.Stack; public class InfixExpressionEvaluation { public static int evaluateInfixExpression(String expression) { Stack<Integer> operandStack = new Stack<>(); Stack<Character> operatorStack = new Stack<>(); for (int i = 0; i < expression.length(); i++) { char ch = expression.charAt(i); if (Character.isDigit(ch)) { StringBuilder num = new StringBuilder(); while (i < expression.length() && Character.isDigit(expression.charAt(i))) { num.append(expression.charAt(i)); i++; } i--; operandStack.push(Integer.parseInt(num.toString())); } else if (ch == '(') { operatorStack.push(ch); } else if (ch == ')') { while (!operatorStack.isEmpty() && operatorStack.peek() != '(') { int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop()); operandStack.push(result); } operatorStack.pop(); } else if (isOperator(ch)) { while (!operatorStack.isEmpty() && precedence(ch) <= precedence(operatorStack.peek())) { int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop()); operandStack.push(result); } operatorStack.push(ch); } } while (!operatorStack.isEmpty()) { int result = performOperation(operatorStack.pop(), operandStack.pop(), operandStack.pop()); operandStack.push(result); } return operandStack.pop(); } public static boolean isOperator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } public static int precedence(char ch) { if (ch == '+' || ch == '-') { return 1; } else if (ch == '*' || ch == '/') { return 2; } return 0; } public static int performOperation(char operator, int operand2, int operand1) { switch (operator) { case '+': return operand1 + operand2; case '-': return operand1 - operand2; case '*': return operand1 * operand2; case '/': if (operand2 == 0) { throw new UnsupportedOperationException("Cannot divide by zero"); } return operand1 / operand2; } return 0; } public static void main(String[] args) { String expression = "1 + 2 * 3"; int result = evaluateInfixExpression(expression); System.out.println("Result: " + result); // 输出:7 } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值