数组实现栈,并计算表达式(中缀表达式)的结果(java实现)

这里主要是计算表达式的结果,比如 “2+3*3-2”,输入一个表达式,计算出最后的结果.用栈实现的思路如下:

1.遍历这个表达式,通过一个变量index记录索引值

2.如果发现遍历出来的字符为一个数字,则直接入栈

3.如果发现遍历出来的字符为一个运算符,则分为以下情况

    3.1 若运算符栈为空,则直接入栈;

    3.2 如果运算符栈有运算符,则进行比较。如果当前运算符的优先级小于等于栈中的运算符的优先级

          就需要从数栈中pop出两个数字,从符号栈中pop出一个运算符,进行运算,得到的结果,在继续

          入数栈,之后,再将当前的运算符入符号栈。如果当前运算符的优先级大于栈中的优先级,则直

         接入符号栈。

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

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

定义一个栈对象

class ArrayStack1{
    private int maxSize;// 栈容量
    private int top = -1;// 栈顶指针
    private int[] stack;// 栈

    // 初始化栈
    public ArrayStack1(int maxSize){
        this.maxSize = maxSize;
        stack = new int[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 = top+1;
        stack[top] = value;
    }

    // 出栈
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈中数据为空...");
        }
        int value = stack[top];
        top = top-1;
        return value;
    }

    // 遍历栈
    public void list(){
        if(isEmpty()){
            System.out.println("栈中数据为空...");
            return;
        }
        for(int i = top;i>=0;i--){
            System.out.printf("arr[%d]=%d",i,stack[i]);
            System.out.println();
        }
    }

    // 查找出栈顶元素
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("栈中数据为空...");
        }
        return stack[top];
    }

    // 找出运算符的优先级
    public int priority(int ch){
        if(ch == '*' || ch == '/')
            return 1;
        else if(ch == '+' || ch == '-')
            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;
            default:
                break;
        }
        return res;
    }

计算表达式结果 ,在这里有一个多位数的运算.当遍历表达式的时候,如果遍历的字符为c,判断他的下一位是否为数字。

若为数字,则拼接keepNum.若为操作符,则对数字进行入栈.记得keepNum清空。

/**
 * @author AN
 * @create 2020-08-31 14:44
 */
public class Calculator {
    public static void main(String[] args) {
        ArrayStack1 operStack = new ArrayStack1(10);// 运算符栈
        ArrayStack1 numStack = new ArrayStack1(10);// 数字栈
        String express = "10+2*6-2";
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int oper;
        int res = 0;
        char c = ' ';
        String keepNum = "";
        while(true){
            c = express.substring(index, index + 1).charAt(0);
            if(operStack.isOper(c)){
                // 如果字符为运算符
                if(operStack.isEmpty()){
                    // 如果符号栈为空,则直接入栈
                    operStack.push(c);
                }else{
                    // 如果符号栈,有操作符,就进行比较
                    // 如果当前操作符的优先级小于等于栈中的操作符,需要从数字栈中pop出两个数字,
                    // 在从符号栈中pop出一个符号,进行运算,将得到的结果,入数栈,然后把当前的操作符入符号栈
                    if(operStack.priority(c) <= operStack.priority(operStack.peek())){
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        oper = operStack.pop();
                        res = operStack.cal(num1,num2,oper);
                        numStack.push(res);
                        operStack.push(c);
                    }else{
                        operStack.push(c);
                    }
                }
            }else{
                // 对多位数进行处理
                keepNum+=c;
                // 如果ch是最后一位,就直接入栈 ‘1’ 或 ‘123’
                if(index == express.length() - 1){
                    numStack.push(Integer.parseInt(keepNum));
                }else{
                    // 判断这个数字下一位是否为数字,若不为数字,则把keepNum入栈.keepNum清空
                    // 若为数字,则继续进行扫描
                    if(operStack.isOper(express.substring(index+1,index+2).charAt(0))){
                        numStack.push(Integer.parseInt(keepNum));
                        // keepNum清空!!!
                        keepNum = "";
                    }
                }
            }
            index++;
            if(index == express.length()){
                break;
            }
        }

        // 当表达式扫描完之后,就顺序的从数栈和符号栈中pop出相对应的数和符号
        // 最后数栈中只有一个数字,就是最后的结果
        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",express,numStack.pop());
    }
}

测试结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值