数据结构——栈(计算器实现原理)

在这里插入图片描述
在这里插入图片描述
实现一个最简单的计算器,规定:

  • 只有+-*/,没有小括号
  • 数字只能是0-9之间的数字,不能有两位数。

Main函数及计算函数代码:

package algorithm.stack;

public class Calculator {
    public static void main(String[] args) {
        String s = "3+6*8/7";
        System.out.println(cal(s));
    }

    public static float cal(String s) {
        int index = 0;
        float num1 = 0;
        float num2 = 0;
        char oper = ' ';
        MyStack numStack = new MyStack(10);
        MyStack operStack = new MyStack(10);
        float result;
        while (index <= s.length() - 1) {
            //如果是字符
            if (MyStack.chType(s.charAt(index)) == 0) {
                //如果是栈空
                if (operStack.isEmpty() || MyStack.priority(s.charAt(index)) > MyStack.priority((char) operStack.peek())) {
                    operStack.push(s.charAt(index));
                }
                //看新的符号优先级小于等于上一个符号
                else if (MyStack.priority(s.charAt(index)) <= MyStack.priority((char) operStack.peek())) {
                    oper = (char) operStack.pop();
                    num1 = numStack.pop();
                    num2 = numStack.pop();
                    result = MyStack.calcu(num1, num2, oper);
                    numStack.push(result);
                    operStack.push(s.charAt(index));
                }

            }
            //如果是数字
            if (MyStack.chType(s.charAt(index)) == 1) {
                numStack.push(s.charAt(index) - 48);
            }
            index++;
        }
        char ch = ' ';
        float n1 = 0;
        float n2 = 0;
        float val;
        //将算式入栈完毕后,计算剩下的数
        while (!operStack.isEmpty()) {
            ch = (char) operStack.pop();
            n1 = numStack.pop();
            n2 = numStack.pop();
            val = MyStack.calcu(n1, n2, ch);
            numStack.push(val);
        }
        return numStack.peek();
    }
}

栈及相关功能:

package algorithm.stack;

public class MyStack {
    //栈的大小
    private final int maxSize;
    //实现栈的数组
    private final float[] stackArray;
    //栈顶
    private int top = -1;

    //构造器
    public MyStack(int maxSize) {
        this.maxSize = maxSize;
        stackArray = new float[maxSize];
    }

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

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

    //入栈
    public void push(float val) {
        if (isFull()) {
            System.out.println("栈满,操作失败!");
            return;
        }
        stackArray[++top] = val;
    }

    //出栈
    public float pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空,出栈失败");
        }
        float val = stackArray[top];
        top--;
        return val;
    }

    //查看栈顶元素
    public float peek() {
        return stackArray[top];
    }

    //遍历栈
    public void show() {
        if (isEmpty()) {
            System.out.println("栈空,打印失败!");
        }
        for (int i = top; i >= 0; i--) {
            System.out.printf("%d\t", stackArray[i]);
            System.out.println();
        }
    }

    //定义符号的优先级
    //+-为0
    //*/为1
    public static int priority(char oper) {
        if (oper == '+' || oper == '-') {
            return 0;
        } else{
            return 1;
        }
    }
    //判断输入的字符是否合法

    /**
     *
     * @param ch
     * @return 0表示是字符,1表示是数字
     */
    public static int chType(char ch){
        String s = "0123456789";
        //是否为字符
        if (ch == '+'||ch == '-'||ch=='*'||ch=='/'){
            return 0;
        }
        //是否为数字
        String temp = String.valueOf(ch);
        if (s.contains(temp)){
            return 1;
        }
        //如果都不是
        throw new RuntimeException("非法字符");
    }

    //计算过程
    public static float calcu(float num1, float num2, char op) {
        float val=0;
        switch (op){
            case '+':
                val = num1+num2;
                break;
            case '-':
                val = num2-num1;
                break;
            case '*':
                val = num1*num2;
                break;
            case '/':
                val = num2/num1;
                break;
            default:break;
        }
        return val;
    }

}

运算结果:

float保存:
在这里插入图片描述
计算器结果:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
是一个非常适合实现计算器数据结构,因为它遵循后进先出(LIFO)的原则,与计算表达式的顺序相符合。下面是一个基于实现计算器的示例代码: ```python class Stack: def __init__(self): self.items = [] def is_empty(self): return len(self.items) == 0 def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() else: return None def peek(self): if not self.is_empty(): return self.items[-1] else: return None def size(self): return len(self.items) def calculate(expression): # 将操作符和操作数分别存储在两个中 operator_stack = Stack() operand_stack = Stack() # 定义一个操作符优先级字典 priority = {'+': 1, '-': 1, '*': 2, '/': 2} # 将表达式按空格分割为一个列表 tokens = expression.split() # 遍历表达式中的每个token for token in tokens: if token.isdigit(): # 如果是数字则压入操作数 operand_stack.push(int(token)) elif token in priority: # 如果是操作符则与操作符中的操作符比较优先级 while (not operator_stack.is_empty()) and \ (priority[operator_stack.peek()] >= priority[token]): # 如果操作符顶的优先级比当前操作符高,则进行计算 operand2 = operand_stack.pop() operand1 = operand_stack.pop() operator = operator_stack.pop() result = eval(str(operand1) + operator + str(operand2)) operand_stack.push(result) # 将当前操作符压入操作符 operator_stack.push(token) # 处理剩余的操作符 while not operator_stack.is_empty(): operand2 = operand_stack.pop() operand1 = operand_stack.pop() operator = operator_stack.pop() result = eval(str(operand1) + operator + str(operand2)) operand_stack.push(result) # 返回最终结果 return operand_stack.pop() ``` 这个实现中,我们使用了两个来存储操作符和操作数。具体实现过程如下: 1. 遍历表达式中的每个token。 2. 如果是数字,则将其压入操作数中。 3. 如果是操作符,则与操作符中的操作符比较优先级。如果操作符顶的优先级比当前操作符高,则进行计算,并将结果压入操作数中;否则,将当前操作符压入操作符中。 4. 处理完表达式中的所有token后,将操作符中剩余的操作符依次弹出并进行计算,直到操作符为空。 5. 返回最终结果。 注意,这个实现中使用了Python内置的`eval()`函数来进行计算。在实际应用中,应该使用更为安全的方法,例如手写计算函数或使用第三方库等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值