好玩的数据结构与算法——利用栈实现简单的计算器(加减乘除)

一、中缀表达式

我们平时见到的算式都是中缀表达式。如:

3+(2+3)*5-2

二、使用中缀表达式实现计算机(加减乘除)

计算表达式 3+2*5-2 的结果。
初始化两个栈,一个数栈(numStack)存放数,一个符号栈(operStack)存放符号。
使用栈完成表达式计算思路:

  1. 通过一个 index 值(索引),来遍历我们的表达式
  2. 如果我们发现是一个数字, 就直接入数栈
  3. 如果发现扫描到是一个符号, 就分如下情况

1 如果发现当前的符号栈为空,就直接入栈
2. 如果符号栈有操作符,就进行比较,如果当前的操作符的优先级小于或者等于栈中的操作符, 就需要从数栈中pop出两个数,在从符号栈中pop出一个符号,进行运算,将得到结果,入数栈,然后将当前的操作符入符号栈, 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.

  1. 当表达式扫描完毕,就顺序的从 数栈和符号栈中pop出相应的数和符号,并运行.
  2. 最后在数栈只有一个数字,就是表达式的结果

代码实现
数组模拟的栈:

public class ArrayStack {

    private int maxsize; // 栈的大小
    private int[] stack; // 数组模拟栈
    private int top = -1; //栈顶,-1表示没有数据

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

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

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

    /**
     * @Description: push 入栈
     */
    public void push(int num){
        if (isFull()){
            System.out.println("栈已满");
            return;
        }
        top++;
        stack[top] = num;
    }

    /**
     * @Description: 出栈
     */
    public int pop(){
        if (isEmpty()){
            throw new RuntimeException("栈空");
        }
        int value = stack[top];
        top--;
        return value;
    }

    /**
     * @Description: priority 返回运算符的优先级,使用数字表示,数字越大,优先级越高
     */
    public int priority(int oper){
        if (oper == '*' || oper == '/'){
            return 1;
        }else if (oper == '+' || oper == '-'){
            return 0;
        }else {
            throw new RuntimeException("未定义改运算符的优先级");
        }
    }

    /**
     * @Description: isOper 判读是否是运算符
     */
    public boolean isOper(char val){
        return val == '+' || val == '-' || val == '*' || val == '/';
    }

    /**
     * @Description: cal 计算结果,因为入栈顺序是从前往后,出栈顺序是从后往前,
     * 所以原来的算式表达式是出栈的第二个数在前。故num2-num1
     * num2 / num1
     */
    public int cal(int num1, int num2, int oper){
        int res = 0;
        switch (oper){
            case '+':
                res = num2 + num1;
                break;
            case  '-':
                res = num2 - num1;
                break;
            case '*':
                res = num2 * num1;
                break;
            case '/':
                res = num2 / num1;
            default:
                break;
        }
        return res;
    }

    /**
     * 查看栈顶元素
     * @return
     */
    public int peek(){
        if (isEmpty()){
            throw new RuntimeException("栈空~~~");
        }
        return stack[top];
    }

    /**
     * @Description: 展示
     */
    public void show(){
        if (isEmpty()){
            System.out.println("栈空~~~");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println("stack["+i+"] = " + stack[i]);
        }
    }
}

计算结果:

public class Calculator {
    public static void main(String[] args) {
        String expression = "10+2*6-2";
        ArrayStack numStack = new ArrayStack(expression.length());
        ArrayStack operStack = new ArrayStack(expression.length());
        // 用于扫描
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';//将每次扫描的插入保存到ch
        String str = "";//将多个字符拼接到
        while (true){
            // 依次得到expression的每一个字符
            ch = expression.substring(index,index+1).charAt(0);
            if (operStack.isOper(ch)){// 是一个运算符
                if (!operStack.isEmpty()){// 运算符栈为空
                    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 {//运算符优先级大于栈顶中的运算符
                        operStack.push(ch); //运算符直接入栈
                    }
                }else {// 运算符栈为空,直接入栈
                    operStack.push(ch); //运算符入栈
                }
            }else {
//                numStack.push(ch - 48); // ch是字符,查看ASCII表,字符和真正的数字直接差了48
                str += ch;
                if (index == expression.length()-1){//到达最后
                    numStack.push(Integer.parseInt(str));
                }else {
                    if (operStack.isOper(expression.substring(index+1, index+2).charAt(0))){ // 下一个字符是符号
                        numStack.push(Integer.parseInt(str));
                        str = "";
                    }
                }
            }
            index ++;
            if (index == expression.length()){
                break;
            }
        }

        numStack.show();

        while (true){
            if (operStack.isEmpty()){ //符号栈为空,这计算结束
                break;
            }
            num1 = numStack.pop();// 取出第一个数栈顶元素
            num2 = numStack.pop();// 取出第二个数栈顶元素
            oper = operStack.pop();//取出符号栈栈顶元素
            res = operStack.cal(num1, num2, oper); //计算结果
            numStack.push(res); //结果入栈
        }
        System.out.printf("表达式%s = %d",expression, numStack.pop());
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

b u g

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

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

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

打赏作者

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

抵扣说明:

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

余额充值