栈-实现综合计算器(中缀表达式)

综合计算器怎么搞?

思路

在这里插入图片描述

Demo1

package datastructres.stack;

/**
 * @author :Yan Guang
 * @date :Created in 2021/1/11 9:41
 * @description:
 */
public class Calculator {
    public static void main(String[] args) {
        String expression = "3+2*6-2";
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;    
        char ch = ' ';
        while (true){
            ch = expression.substring(index,index+1).charAt(0);
            //首先判断ch是什么,然后进行操作
            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 = operStack.cal(num1, num2, oper);
                        numStack.push(res);
                        operStack.push(ch);
                    }else {
                        //入栈
                        operStack.push(ch);
                    }
                }else {
                    //如果为空,直接入栈
                    operStack.push(ch);
                }
            }else{
                //因为numStack里面存放的是int类型的,这里存放值的时候需要对照ASCII码表进行对照
                //但是int类型可以与char类型直接进行比较
                numStack.push(ch-48);
            }
            index++;
            if (index>=expression.length()){
                break;
            }
        }
        //现在扫描已经结束,需要继续处理完两个栈中的元素
        while (true){
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        //最后存放在numStack里面的元素就是结果了
        System.out.printf("表达式%s = %d",expression,numStack.pop());
    }
}

class ArrayStack2 {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack2(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 peek(){
        return stack[top];
    }

    public int pop() {
        if (isEmpty()) {
            //throw相当于已经停止了代码,所以不用return
            //当存在返回值的时候(不为void)的时候,我们尽量可以抛出一个异常来代替return
            throw new RuntimeException("栈空,无法取出数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void showStack() {
        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 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;
            default:
                break;
        }
        return res;
    }
}

这里存在的问题就是只能进行一位数运算,无法计算大于10的数,而且只有加减乘除四个运算符~

下面是优化之后的代码,具体也就改了一个地方,有很多注释的地方,大家看看吧

Demo2

package datastructres.stack;

/**
 * @author :Yan Guang
 * @date :Created in 2021/1/11 9:41
 * @description:
 */
public class Calculator {
    public static void main(String[] args) {
        String expression = "70+2*6-4";
        ArrayStack2 numStack = new ArrayStack2(10);
        ArrayStack2 operStack = new ArrayStack2(10);
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int oper = 0;
        int res = 0;
        char ch = ' ';
        String keepNum="";
        while (true){
            ch = expression.substring(index,index+1).charAt(0);
            //首先判断ch是什么,然后进行操作
            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 = operStack.cal(num1, num2, oper);
                        numStack.push(res);
                        operStack.push(ch);
                    }else {
                        //入栈
                        operStack.push(ch);
                    }
                }else {
                    //如果为空,直接入栈
                    operStack.push(ch);
                }
            }else{
                //因为numStack里面存放的是int类型的,这里存放值的时候需要对照ASCII码表进行对照
                //但是int类型可以与char类型直接进行比较
                //1.
                //1.当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
                //2.在处理数,需要向expression的表达式的index后再看-位,如果是数就进行扫描,如果是符号才入栈
                //3.因此我们需要定义一个变量字符串,用于拼接
                // numStack.push(ch-48);
                keepNum+=ch;
                //如果当此时的数为最后一个数字数,就直接入栈
                if (index==expression.length()-1){
                    numStack.push(Integer.parseInt(keepNum));
                }else {
                    //这里会存在一个越界问题,如果index到了最后一个,就没有index+1了
                    if (operStack.isOper(expression.substring(index + 1, index + 2).charAt(0))) {//判断是否是运算符
                        numStack.push(Integer.parseInt(keepNum));
                        keepNum = "";
                    }
                }
            }
            index++;
            if (index>=expression.length()){
                break;
            }
        }
        //现在扫描已经结束,需要继续处理完两个栈中的元素
        while (true){
            if (operStack.isEmpty()){
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            oper = operStack.pop();
            res = operStack.cal(num1, num2, oper);
            numStack.push(res);
        }
        //最后存放在numStack里面的元素就是结果了
        System.out.printf("表达式%s = %d",expression,numStack.pop());
    }
}

class ArrayStack2 {
    private int maxSize;
    private int[] stack;
    private int top = -1;

    public ArrayStack2(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 peek(){
        return stack[top];
    }

    public int pop() {
        if (isEmpty()) {
            //throw相当于已经停止了代码,所以不用return
            //当存在返回值的时候(不为void)的时候,我们尽量可以抛出一个异常来代替return
            throw new RuntimeException("栈空,无法取出数据~");
        }
        int value = stack[top];
        top--;
        return value;
    }

    public void showStack() {
        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 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;
            default:
                break;
        }
        return res;
    }
}

欢迎大家在评论区讨论哟~

实现计算器的核心数据结构,可以用来存储运算符和操作数。下面是使用实现中缀表达式计算器的C语言代码: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <ctype.h> #define MAX_SIZE 50 typedef struct { int top; int data[MAX_SIZE]; } Stack; void push(Stack *s, int value) { if (s->top == MAX_SIZE - 1) { printf("Stack Overflow\n"); return; } s->data[++(s->top)] = value; } int pop(Stack *s) { if (s->top == -1) { printf("Stack Underflow\n"); exit(1); } return s->data[(s->top)--]; } bool is_operator(char ch) { return ch == '+' || ch == '-' || ch == '*' || ch == '/'; } int get_priority(char op) { switch (op) { case '(': return 0; case '+': case '-': return 1; case '*': case '/': return 2; default: return -1; } } int calculate(int op1, int op2, char operator) { switch (operator) { case '+': return op1 + op2; case '-': return op1 - op2; case '*': return op1 * op2; case '/': return op1 / op2; default: return -1; } } int evaluate_expression(char *expression) { Stack operand_stack; Stack operator_stack; operand_stack.top = -1; operator_stack.top = -1; int i = 0; while (expression[i] != '\0') { if (isdigit(expression[i])) { int operand = 0; while (isdigit(expression[i])) { operand = operand * 10 + (expression[i] - '0'); i++; } push(&operand_stack, operand); } else if (is_operator(expression[i])) { while (operator_stack.top >= 0 && get_priority(expression[i]) <= get_priority(operator_stack.data[operator_stack.top])) { int op2 = pop(&operand_stack); int op1 = pop(&operand_stack); char op = pop(&operator_stack); int result = calculate(op1, op2, op); push(&operand_stack, result); } push(&operator_stack, expression[i]); i++; } else if (expression[i] == '(') { push(&operator_stack, expression[i]); i++; } else if (expression[i] == ')') { while (operator_stack.data[operator_stack.top] != '(') { int op2 = pop(&operand_stack); int op1 = pop(&operand_stack); char op = pop(&operator_stack); int result = calculate(op1, op2, op); push(&operand_stack, result); } pop(&operator_stack); i++; } else { i++; } } while (operator_stack.top >= 0) { int op2 = pop(&operand_stack); int op1 = pop(&operand_stack); char op = pop(&operator_stack); int result = calculate(op1, op2, op); push(&operand_stack, result); } return pop(&operand_stack); } int main() { char str[MAX_SIZE]; printf("Enter expression: "); scanf("%s", str); int result = evaluate_expression(str); printf("Result: %d\n", result); return 0; } ``` 这个程序支持加、减、乘、除和括号,可以计算包括负数在内的表达式。你可以在控制台中输入一个表达式,程序会输出计算结果。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值