【数据结构】使用栈实现综合计算器

 首先初始化两个栈,数栈(numStack)用于存放数据符号栈(operStack)用于存放运算符

计算思路

1.通过一个index值(索引)来遍历表达式

2.如果发现扫描到一个数字,就直接入数栈

3.如果发现扫描到一个符号,就分如下情况

①如果当前符号栈为空,就直接入符号栈

②如果符号栈有操作符,就进行比较,如果当前操作符的优先级小于或者等于栈中的操作符,就需要从数栈中 pop 出两个数进行运算,运算结果入数栈,然后将当前操作符入符号栈;如果当前操作符的优先级大于栈中的的操作符,就直接入符号栈

4.当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运算

5.最后数栈中只有一个数字,就是表达式的结果

判断运算符优先级

//返回运算符的优先级,优先级由程序员来确定,优先级使用数字表示
//数字越大优先级越高
public int priority(int oper) {
    if (oper == '+' || oper == '-') {
        return 0;
    } else if (oper == '*' || oper == '/') {
        return 1;
    } else {
        return -1;  //假定目前的表达式只有+,-,*,/
    }
}

判断是否为运算符

public boolean isOper(char val) {
    return val == '+' || val == '-' || val == '*' || val == '/';
}

进行运算

public int cal(int num1, int num2, char oper) {
    int res = 0;  //res 用于存放计算的结果
    switch (oper) {
        case '+':
            res = num1 + num2;
            break;
        case '-':
            res = num2 - num1;
            break;
        case '*':
            res = num1 * num2;
            break;
        case '/':
            res = num2 / num1;
            break;
        default:
            break;
    }
    return res;
}
个位数基本运算
public class Calculator {
    public static void main(String[] args) {
        String expression = "7+2*6-4";
        //创建两个栈,数栈,符号栈
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        //定义需要的相关变量
        int index = 0;
        int num1;
        int num2;
        int oper;
        int res;
        char ch;  //将每次扫描得到的char保存到ch
        //开始while循环扫描expression
        while (true) {
            //依次得到 expression 中的每个字符
            ch = expression.charAt(index);
            //判断ch是什么,然后做相应的处理
            if (operStack.isOper(ch)) {  //如果是运算符
                //判断当前的符号栈是否为空
                if (!operStack.isEmpty()) {
                    /*
                    如果符号栈有操作符,就进行比较,
                    如果当前操作符的优先级小于或者等于栈中的操作符,
                    就需要从数栈中 pop 出两个数进行运算,运算结果入数栈,
                    然后将当前操作符入符号栈
                     */
                    if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.cal(num1, num2, oper);
                        //把运算结果入数栈
                        numStack.push(res);
                    }
                }
                //将操作符入符号栈
                operStack.push(ch);
            } else {
                numStack.push(ch -'0');
            }
            //让 index++ ,并判断是否扫描到 expression 最后
            index++;
            if (index == expression.length()) {
                break;
            }
        }
        //当表达式扫描完毕,就顺序的从数栈和符号栈中 pop 出相应的数和符号,并运行
        while (!operStack.isEmpty()) {
            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());
    }
}

//先创建一个栈
//定义一个 ArrayStack 表示栈
class ArrayStack2 {
    private int maxSize;  //栈的大小
    private int[] stack;  //数组,数组模拟栈,数据就放在该数组
    private int top = -1;  //top 表示栈顶,初始化为 -1

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

    //栈满
    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;
        }
        stack[++top] = value;
    }

    //出栈 - pop
    public int pop() {
        //先判断栈是否空
        if (isEmpty()) {
            //抛出异常
            throw new RuntimeException("栈为空,不能取出数据");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //返回栈顶数据,但不出栈 - peek
    public int peek() {
        return stack[top];
    }

    //显示栈的情况(遍历栈),遍历时,需要从栈顶开始显示数据
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空,没有数据");
            return;
        }
        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 0;
        } else if (oper == '*' || oper == '/') {
            return 1;
        } 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;  //res 用于存放计算的结果
        switch (oper) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }
}

以上代码有一个缺陷,它只能做个位数的运算

整数基本运算

以下代码修改了从字符串中取出整数的思路,可以处理多位数

public class Calculator {
    public static void main(String[] args) {
        String expression = "70+20*6-4";
        //创建两个栈,数栈,符号栈
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        //定义需要的相关变量
        int index = 0;
        int num1;
        int num2;
        int oper;
        int res;
        char ch;  //将每次扫描得到的char保存到ch
        String keepNum = "";
        //开始while循环扫描expression
        while (true) {
            //依次得到 expression 中的每个字符
            ch = expression.charAt(index);
            //判断ch是什么,然后做相应的处理
            if (operStack.isOper(ch)) {  //如果是运算符
                //判断当前的符号栈是否为空
                if (!operStack.isEmpty()) {
                    /*
                    如果符号栈有操作符,就进行比较,
                    如果当前操作符的优先级小于或者等于栈中的操作符,
                    就需要从数栈中 pop 出两个数进行运算,运算结果入数栈,
                    然后将当前操作符入符号栈
                     */
                    if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = numStack.cal(num1, num2, oper);
                        //把运算结果入数栈
                        numStack.push(res);
                    }
                }
                //将操作符入符号栈
                operStack.push(ch);
            } else {  //如果是数,则直接入数栈

                /*
                分析思路
                1.当处理多位数时,不能发现是一个数就立即入栈,因为可能是多位数
                2.向 expression 的表达式的 index 后再看一位,如果是数就进行扫描,如果是符号才入栈
                3.因此定义一个字符串变量用于拼接
                 */

                //处理多位数
                keepNum += ch;

                //如果 ch 已经是 expression 的最后一位,就直接入栈
                if (index == expression.length() - 1) {
                    numStack.push(Integer.parseInt(keepNum));
                } else {
                    //判断下一个字符是不是数字,如果是数字,就继续扫描,如果是运算符则入栈
                    if (operStack.isOper(expression.substring(index + 1,index + 2).charAt(0))) {
                        //如果最后一位是运算符,则入栈 keepNum = "1" 或者 "123"
                        numStack.push(Integer.parseInt(keepNum));
                        //重要的!!!keepNum 清空
                        keepNum = "";
                    }
                }
            }
            //让 index++ ,并判断是否扫描到 expression 最后
            index++;
            if (index == expression.length()) {
                break;
            }
        }
        //当表达式扫描完毕,就顺序的从数栈和符号栈中 pop 出相应的数和符号,并运行
        while (!operStack.isEmpty()) {
            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());
    }
}

//先创建一个栈
//定义一个 ArrayStack 表示栈
class ArrayStack2 {
    private int maxSize;  //栈的大小
    private int[] stack;  //数组,数组模拟栈,数据就放在该数组
    private int top = -1;  //top 表示栈顶,初始化为 -1

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

    //栈满
    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;
        }
        stack[++top] = value;
    }

    //出栈 - pop
    public int pop() {
        //先判断栈是否空
        if (isEmpty()) {
            //抛出异常
            throw new RuntimeException("栈为空,不能取出数据");
        }
        int value = stack[top];
        top--;
        return value;
    }

    //返回栈顶数据,但不出栈 - peek
    public int peek() {
        return stack[top];
    }

    //显示栈的情况(遍历栈),遍历时,需要从栈顶开始显示数据
    public void list() {
        if (isEmpty()) {
            System.out.println("栈空,没有数据");
            return;
        }
        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 0;
        } else if (oper == '*' || oper == '/') {
            return 1;
        } 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;  //res 用于存放计算的结果
        switch (oper) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
            default:
                break;
        }
        return res;
    }
}

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值