JAVA Data Structure-06 (2) Application of Stack Structure Calculation of Simple Calculation Expression (Infix Expression)

JAVA data structure learning-06 stack

JAVA data structure-06 (1) The basic data structure realization of the stack (array realization, linked list realization)
JAVA data structure-06 (3) The application of the stack structure three kinds of expressions before suffix, infix expression to suffix expression reverse Polish Calculator implementation and algorithm ideas

2. Application of stack structure (expression and calculator)

2.1 Calculation of simple calculation expression (infix expression)

70*2*2-5+1-5-3+4

Implementation ideas :

  • Set up 2 stack structures, a number stack numStack is only used to store numbers; a symbol stack operStack is only used to store symbols.
  • Traverse our expression through an index value;
  • If the index value is found to be a number, it directly enters the symbol stack;
  • If a symbol is found: There are three situations:
    • If the symbol stack is empty, just push it directly
    • If the symbol stack is not empty and the priority of the operator scanned by the current index is less than or equal to the operator at the top of the stack, you need to pop 2 data from the number stack, pop a symbol from the symbol stack, and perform the binary operation ( Subtraction and division need to pay attention to who subtracts/divides whom); put the result into the number stack, and then push the current operator into the symbol stack.
    • If the symbol stack is not empty and the priority of the operator scanned by the current index is greater than the operator at the top of the stack, it is directly pushed onto the stack.
  • When the expression is scanned, the number in the expression and the intermediate value of the operation with higher priority will be stored in the number stack, and the operator with the priority decreasing from the top of the stack will be stored in the symbol stack;
  • Therefore, you can directly perform calculations in the order of the symbol stack, pop an operator from the symbol stack in sequence, pop 2 numbers from the number stack, and push the result of the operation back to the number stack after performing the operation;
  • When the operator stack is empty, the number on the top of the stack is the final operation result.

Prepare the stack structure : (Java bottom layer will convert char to int, so char and int can be directly compared)

​ Add three methods to determine whether it is an operator, priority, and perform calculation

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

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

    public boolean isFull() {
    
    
        return top == maxSize - 1;
    }

    public boolean isEmpty() {
    
    
        return top == -1;
    }

    public int getTop(){
    
    
        if(isEmpty()){
    
    
            throw new RuntimeException("栈空");
        }
        return stack[top];
    }

    public void push(int data){
    
    
        if(isFull()){
    
    
            System.out.println("栈满,无法压入数据");
            return;
        }
        top++;
        stack[top] = data;
    }

    public int pop(){
    
    
        if(isEmpty()){
    
    
            throw new RuntimeException("栈为空,无法取出数据");
        }
        int value = stack[top];
        top --;
        return value;
    }

    public void showStack(){
    
    
        if(isEmpty()){
    
    
            System.out.println("栈为空");
            return ;
        }
        for (int i = top; i >=0 ; i--) {
    
    
            System.out.printf("stack[%d] = %d \n",i,stack[i]);
        }
    }

    //判断是否是操作符
    //char 底层也是转换为int 所有可用直接进行比较
    public boolean isOper(int value){
    
    
        return value == '+' || value == '-' || value == '*' || value == '/';
    }

    //返回操作符的优先级 */优先级高于+-
    public int priority(int value){
    
    
        if(value == '*' || value == '/'){
    
    
            return 1;
        }
        if(value == '+' || value == '-'){
    
    
            return 0;
        }
        return -1;
    }

    //执行计算
    public int calculation (int num1,int num2,int oper){
    
    
        int res = 0;
        switch (oper){
    
    
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num1 - num2;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num1 / num2;
                break;
        }
        return res;
    }
}

Idea realization :


public class Caculator {
    
    
    public  static void main(String args[]){
    
    
        //1.创建过程中需要使用的变量
        ArrayStack numStack = new ArrayStack(10);
        ArrayStack operStack = new ArrayStack(10);
        String expression = "70+2*6-4";
        int num1;
        int num2;
        int oper;
        int res = 0;
        int index = 0;
        char ch = ' ';
        String number= "";
        while (true){
    
    
            //获取ch
            ch = expression.charAt(index);
            if(numStack.isOper(ch)){
    
    
                //是符号进行下一步判断
                if(operStack.isEmpty()){
    
    
                    //直接进栈
                    operStack.push(ch);
                }else {
    
    
                    if(operStack.priority(ch) <= operStack.priority(operStack.getTop())){
    
    
                        //需要从数栈中pop出2个数据,从符号栈中pop出一个符号,执行二元运算(减法和除法需要注意谁减/除谁);
                        //将得到的结果入数栈,然后在将当前操作符压入符号栈中.
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.calculation(num2, num1,oper);
                        numStack.push(res);
                        operStack.push(ch);
                    }else {
    
    
//                    直接入栈.
                        operStack.push(ch);
                    }
                }
            } else {
    
    

                number += ch;
                if(index == expression.length() -1){
    
    
                    numStack.push(Integer.parseInt(number));
                }else {
    
    
                    //处理多位数,需要看index位置的后一位是否还是数字,如果是,就需要进行拼接.如果是操作符,则直接入栈
                    if(operStack.isOper(expression.charAt(index+1))){
    
    
                        //直接将string入栈
                        numStack.push(Integer.parseInt(number));
                        number = "";
                    }
                }
            }
            index++;
            if(index >= expression.length()){
    
    
                break;
            }
        }
        //数据处理完成.执行计算
        while (true){
    
    
            if(operStack.isEmpty()) break;
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = numStack.calculation(num2, num1,oper);
            numStack.push(res);
        }

        System.out.println("最后的计算结果为:"+numStack.pop());

    }
}

Guess you like

Origin blog.csdn.net/weixin_44634197/article/details/108552118