datastructure:栈实现计算器

使用栈完成表达式的计算思路
    1. 通过一个 index 值(索引),遍历表达式
    2. 如果是一个数字, 直接入数栈
    3. 如果是一个符号, 分如下情况
        3.1 如果当前的符号栈为空,直接入栈
        3.2 如果符号栈有操作符,进行比较:
            3.2.1 如果当前的操作符的优先级小于或者等于栈中的操作符,从数栈中pop出两个数,符号栈中pop出一个符号,进行运算,
                  将得到的结果,入数栈,然后将当前的操作符入符号栈,
            2.2.2 如果当前的操作符的优先级大于栈中的操作符, 就直接入符号栈.
    4. 当表达式扫描完毕,就顺序地从数栈和符号栈中pop出相应的数和符号,并运行.
    5. 最后在数栈只有一个数字,就是表达式的结果
public class Calculator {
    public static void main(String[] args) {
        // 运算表达式
        String expression = "2-2*2+5";
        // 创建数字栈和运算符栈
        ArrayStack numStack = new ArrayStack(10);
        ArrayStack operStack = new ArrayStack(10);
        // 定义需要的相关变量
        // 扫描的指针
        int index = 0;
        // 计算的两个数字
        int num1 = 0;
        int num2 = 0;
        // 操作符
        int oper = 0;
        // 计算结果
        int res = 0;
        // 每次扫描得到的字符保存到ch
        char ch = ' ';
        String keepNum = "";

        while (true) {
            // 依次得到一个字符
            ch = expression.charAt(index);
            // 如果字符是一个运算符
            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 {
                // 处理多位数时,需要看后一位,如果是数就继续扫描,如果是符号才入栈
                // 需要定义一个字符串变量,用于拼接
                keepNum += ch;
                // 如果ch已经是expression的最后一位,不用判断,直接入栈
                if (index == expression.length() - 1) {
                    numStack.push(Integer.parseInt(keepNum));
                } else {
                    // 判断下一个字符是不是数字,是数字就继续扫描
                    if (operStack.isOper(expression.charAt(index + 1))) {
                        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();
            if (!operStack.isEmpty() && operStack.peek() == '-') {
                oper = operStack.peek();
            }
            res = numStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        System.out.println("表达式" + expression + "的运算结果为" + numStack.pop());
    }
}

class ArrayStack {
    // 定义栈的大小
    private int maxSize;
    // 用数组模拟栈,数据放在数组中
    private int[] stack;
    // top表示栈顶,初始化为-1
    private int top = -1;

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

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

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

    // 入栈
    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 display() {
        if (isEmpty()) {
            System.out.println("栈已空,没有数据!");
            return;
        }
        for (int i = top; i >= 0; i--) {
            System.out.println("stack[" + 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 oper) {
        return oper == '+' || oper == '-' || oper == '*' || oper == '/';
    }

    // 计算方法
    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;
                break;
            default:
                System.out.println("运算符输入错误!");
        }
        return res;
    }

    // 返回当前栈的栈顶的值,不出栈
    public int peek() {
        return stack[top];
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值