数据结构- 栈(实现综合计算器)(一位数计算 扩展到 多位数计算)

思路

在这里插入图片描述

代码(可以看到这里的数字只能是单位数字,那么如何改成可以是多位数呢?!往下看)

package stack;

public class Calculator {
    public static void main(String[] args) {
        //完成表达式运算
        String expression = "7+2*6-2*2";
        //创建两个栈,一个数栈,一个符号栈
        ArrayStack1 numstack = new ArrayStack1(10);
        ArrayStack1 operstack = new ArrayStack1(10);
        //定义需要的相关变量
        int index = 0; //用于扫描
        int num1 = 0, num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';//将每次扫描得到的char保存给ch
        //开始while循环的扫描expression
        while(true){
            //一次得到expression 的每个字符
            ch = expression.substring(index,index+1).charAt(0);
            //判断ch是字符还是数字
            if (operstack.isOper(ch)){
                //判断符号栈是否为空
                if (!operstack.isEmpty()){
                    //如果不为空,比较,如果当前操作符小于等于则进行下面操作
                    if (operstack.priority(ch) <= operstack.priority(operstack.peekTop())){
                        num1 = numstack.pop();
                        num2 = numstack.pop();
                        oper = operstack.pop();
                        res = numstack.cal(num1,num2,oper);
                        //把运算的结果加入栈
                        numstack.push(res);
                        //然后将当前操作符入符号栈
                        operstack.push(ch);
                    }else {
                        operstack.push(ch);
                    }
                }else {
                    //为空直接入栈
                    operstack.push(ch);
                }
            }else {//如果是数直接入栈(这里的1是字符'1',要转成数字1,ascll码减48)
                numstack.push(ch - 48);
            }
            //让index + 1,判断是否扫描到expression最后
            index ++;
            if (index >= expression.length()){
                break;
            }
        }

        //扫描表达式完毕后,就顺序的从 数栈和符号栈中pop出相应的数和符合,并运算
        while (true){
            //如果符号栈为空,则计算得到最后的结果,数栈中只有一个数字
            if (operstack.isEmpty()){
                break;
            }
            num1 = numstack.pop();
            num2 = numstack.pop();
            oper = operstack.pop();
            res = numstack.cal(num1,num2,oper);
            numstack.push(res);
        }
        //打印结果(就是数栈中的最后一个数)
        System.out.printf("表达式 %s = %d",expression,numstack.pop());

    }
}

class ArrayStack1{
    private int maxSize; //栈大小
    private int[] stack;//数组模拟栈,数据放入数组里
    private int top = -1; //top表示栈顶,初始化为-1

    //构造器
    public ArrayStack1(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //返回栈顶的值,不出栈
    public int peekTop(){
        return stack[top];
    }
    //栈满
    public boolean isFull(){
        return top == maxSize - 1;
    }

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

    // 入栈 push
    public void push(int value){
        //判断栈是否满
        if (isFull()){
            System.out.println("栈满,不能入栈");
            return;
        }
        top++;
        stack[top] = value;
    }

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

    //遍历栈(从栈顶开始)
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
        }
        for (int i = top; i>=0; i--){
            System.out.printf("stack[%d] = %d\n",i,stack[i]);
        }
    }

    //返回运算符优先级,优先级有程序员来确定,优先级使用数字表示
    //数字越大,优先级越高
    public int priority(int oper){
        if (oper == '*' || oper == '/'){
            return 1;
        }else if(oper == '+' || oper == '-'){
            return 0;
        }else {
            return -1;//假定目前的表达式只有 +-*/
        }
    }
    //判断是否是一个运算符
    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*' || val == '/';
    }
    //计算方法
    public int cal(int num1, int num2, int oper){
        int res = 0; //计算结果
        switch (oper){
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1; //注意顺序
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
        }
        return res;
    }
}

找到是哪个地方有问题?,发现是一个数字就直接入栈了,那么需要在入数栈时,需要向后看,如果是数就拼接并继续扫描,如果是符合才入栈。(那么就需要一个字符串变量用于拼接)

代码

package stack;

public class Calculator {
    public static void main(String[] args) {
        //完成表达式运算
        String expression = "71+2*6-2*2";
        //创建两个栈,一个数栈,一个符号栈
        ArrayStack1 numstack = new ArrayStack1(10);
        ArrayStack1 operstack = new ArrayStack1(10);
        //定义需要的相关变量
        int index = 0; //用于扫描
        int num1 = 0, num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';//将每次扫描得到的char保存给ch
        String keepnum = ""; //用于拼接多位数
        //开始while循环的扫描expression
        while(true){
            //一次得到expression 的每个字符
            ch = expression.substring(index,index+1).charAt(0);
            //判断ch是字符还是数字
            if (operstack.isOper(ch)){
                //判断符号栈是否为空
                if (!operstack.isEmpty()){
                    //如果不为空,比较,如果当前操作符小于等于则进行下面操作
                    if (operstack.priority(ch) <= operstack.priority(operstack.peekTop())){
                        num1 = numstack.pop();
                        num2 = numstack.pop();
                        oper = operstack.pop();
                        res = numstack.cal(num1,num2,oper);
                        //把运算的结果加入栈
                        numstack.push(res);
                        //然后将当前操作符入符号栈
                        operstack.push(ch);
                    }else {
                        operstack.push(ch);
                    }
                }else {
                    //为空直接入栈
                    operstack.push(ch);
                }
            }else {//如果是数直接入栈(这里的1是字符'1',要转成数字1,ascll码减48)
                //如果有多位数,则需要改进代码,不能直接入栈
                //思路:
                // 1.扫描到数字,需要继续向后扫描,如果是数就拼接,继续扫描,直到扫描是字符
                keepnum += ch;

                //如果ch是最后一位了则直接入栈
                if (index == expression.length()-1){
                    numstack.push(Integer.parseInt(keepnum));
                }else {
                    //判断下一个字符是不是数字,如果是继续扫描
                    if (operstack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {
                        numstack.push(Integer.parseInt(keepnum));
                        //这里一定要清空keepnum
                        keepnum = "";
                    }
                }
            }
            //让index + 1,判断是否扫描到expression最后
            index ++;
            if (index >= expression.length()){
                break;
            }
        }

        //扫描表达式完毕后,就顺序的从 数栈和符号栈中pop出相应的数和符合,并运算
        while (true){
            //如果符号栈为空,则计算得到最后的结果,数栈中只有一个数字
            if (operstack.isEmpty()){
                break;
            }
            num1 = numstack.pop();
            num2 = numstack.pop();
            oper = operstack.pop();
            res = numstack.cal(num1,num2,oper);
            numstack.push(res);
        }
        //打印结果(就是数栈中的最后一个数)
        System.out.printf("表达式 %s = %d",expression,numstack.pop());

    }
}

class ArrayStack1{
    private int maxSize; //栈大小
    private int[] stack;//数组模拟栈,数据放入数组里
    private int top = -1; //top表示栈顶,初始化为-1

    //构造器
    public ArrayStack1(int maxSize) {
        this.maxSize = maxSize;
        stack = new int[this.maxSize];
    }

    //返回栈顶的值,不出栈
    public int peekTop(){
        return stack[top];
    }
    //栈满
    public boolean isFull(){
        return top == maxSize - 1;
    }

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

    // 入栈 push
    public void push(int value){
        //判断栈是否满
        if (isFull()){
            System.out.println("栈满,不能入栈");
            return;
        }
        top++;
        stack[top] = value;
    }

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

    //遍历栈(从栈顶开始)
    public void list(){
        if (isEmpty()){
            System.out.println("栈空");
        }
        for (int i = top; i>=0; i--){
            System.out.printf("stack[%d] = %d\n",i,stack[i]);
        }
    }

    //返回运算符优先级,优先级有程序员来确定,优先级使用数字表示
    //数字越大,优先级越高
    public int priority(int oper){
        if (oper == '*' || oper == '/'){
            return 1;
        }else if(oper == '+' || oper == '-'){
            return 0;
        }else {
            return -1;//假定目前的表达式只有 +-*/
        }
    }
    //判断是否是一个运算符
    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*' || val == '/';
    }
    //计算方法
    public int cal(int num1, int num2, int oper){
        int res = 0; //计算结果
        switch (oper){
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1; //注意顺序
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
        }
        return res;
    }
}

发布了83 篇原创文章 · 获赞 61 · 访问量 9197

猜你喜欢

转载自blog.csdn.net/weixin_43736084/article/details/102020304