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

一、基本介绍

二、应用实例

package stack;

public class InffixExpression {
    public static void main(String[] args) {
        String inffixExpression = "7*2*2-5+1-5+3-4";
        InffixStack numStack = new InffixStack(16);
        InffixStack operStack = new InffixStack(16);
        int index = 0;
        int num1 = 0;
        int num2 = 0;
        int res = 0;
        int op = 0;
        char ch = ' ';
        String numStr = "";
        while (true) {
            //  取出字符串里的每一个字符
            ch = inffixExpression.substring(index, index + 1).charAt(0);
            //  判断是否是符号
            if (operStack.isOper(ch)) {
                if (operStack.isEmpty()) {
                    //  当前栈为空,直接入栈
                    operStack.push(ch);
                } else {
                    //  栈不为空,判断当前操作符的优先级是否小于等于栈中的操作符
                    if (operStack.priority(ch) <= operStack.priority((char)operStack.peek())) {
                        num1 = numStack.pop();
                        num2 = numStack.pop();
                        op = operStack.pop();
                        res = numStack.cal(num1, num2, op);
                        numStack.push(res);
                        operStack.push(ch);
                    } else {
                        //  当前操作符的优先级大于栈中的操作符
                        operStack.push(ch);
                    }
                }
            } else {
                // 如果是数字,需要考虑多位数字
                numStr += ch;
                //  如果ch是最后一位,则直接入栈
                if (index == inffixExpression.length() - 1) {
                    numStack.push(Integer.parseInt(numStr));
                } else {
                    // 判断下一位是数字还是字符,若是数字,则直接进行下一轮循环。反之,则将当前数字存入数字栈中
                    if (operStack.isOper(inffixExpression.substring(index + 1, index + 2).charAt(0))) {
                        numStack.push(Integer.parseInt(numStr));
                        numStr = ""; // 下一次用来重新拼接数字,每次要清空
                    }
                }

            }
            //  每次查完一个字符后,index自增
            index++;
            //  判断表达式是否已扫描完
            if (index >= inffixExpression.length()){
                break;
            }
        }

        //  遍历完字符串后,从栈中取出数据进行运算,直到符号栈为空退出
        while (true) {
            if (operStack.isEmpty()) {
                break;
            }
            num1 = numStack.pop();
            num2 = numStack.pop();
            op = operStack.pop();
            res = numStack.cal(num1, num2, op);
            numStack.push(res);
        }
        //  符号栈为空时,数字栈的中的数字就是运算结果
        System.out.println(inffixExpression + "=" +  numStack.pop());
    }
}

class InffixStack {
    private int[] arr;
    private int maxSize;
    private int top;
    public InffixStack(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[maxSize];
        this.top = -1;
    }

    public int peek() {
        return arr[top];
    }

    public void push(int val) {
        if (isFull()) {
            throw new RuntimeException("栈满,入栈失败!");
        }
        arr[++top] = val;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,出栈失败!");
        }
        return arr[top--];
    }

    public void print() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,出栈失败!");
        }
        System.out.print("栈元素:");
        for (int i = top; i >= 0 ; i--) {
            System.out.print(arr[i] + " ");
        }
        System.out.println();
    }

    public boolean isEmpty() {
        if (top == -1) {
            return true;
        }
        return false;
    }

    public boolean isFull() {
        if (top == maxSize - 1) {
            return true;
        }
        return false;
    }

    public boolean isOper(char ch) {
        if (ch == '+' || ch == '-' || ch == '*' || ch == '/') {
            return true;
        }
        return false;
    }

    public int priority(char ch) {
        if (ch == '*' || ch == '/') {
            return 1;
        } else if (ch == '+' || ch == '-') {
            return 0;
        } else {
            return -1;
        }
    }

    public int cal(int num1, int num2, int op) {
        int res = 0;
        switch (op) {
            case '+':
                res = num1 + num2;
                break;
            case '-':
                res = num2 - num1;
                break;
            case '*':
                res = num1 * num2;
                break;
            case '/':
                res = num2 / num1;
                break;
        }
        return res;
    }
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
实现计算器的核心数据结构,可以用来存储运算符和操作数。下面是使用实现中缀表达式计算器的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; } ``` 这个程序支持加、减、乘、除和括号,可以计算包括负数在内的表达式。你可以在控制台中输入一个表达式,程序会输出计算结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

来得晚一些也行

观众老爷,请赏~

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

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

打赏作者

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

抵扣说明:

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

余额充值