用栈实现综合计算器

it2025-04-05  8

思路分析代码实现 package org.structure.stack; /** * 使用栈实现综合计算器 * @author cjj_1 * @date 2020-08-06 10:30 */ public class IntegratedCalculatorStack { public static void main(String[] args) { //定义要计算的表达式 String expresion = "300+8*4-4"; //定义两个栈 分别存放 操作数,和操作符 Stack4Calcalator numStack = new Stack4Calcalator(10); Stack4Calcalator operStack = new Stack4Calcalator(10); //定义辅助变量 int index=0; int num1; int num2; int oper; int res =0; char ch ; String keepNum; //开始遍历 表达式 while (expresion.length() != index){ ch = expresion.charAt(index); if(isOper(ch)){//如果是操作符 if(operStack.isEmpty()){ operStack.pushOne(ch); }else {//如果不是空的比对栈顶元素的的优先级 if(priority(ch)<=priority(operStack.picck())){ oper = operStack.pop(); num1 = numStack.pop(); num2 = numStack.pop(); res = calcalator(num1,num2,oper); numStack.pushOne(res); operStack.pushOne(ch); }else { operStack.pushOne(ch); } } }else { String keepNum1 = expresion.substring(index,index+1); /*循环内 判断 index 下一个指针中指的是啥,分三种情况 1,是空(index指向的字符已经是最后一个字符了) 2,是操作符, 3,是数字 */ while (true){ //1,2,两种情况 if(index+1 == expresion.length() || isOper(expresion.charAt(index+1))) break; //3,中情况,index 指针往后移动 keepNum1+= expresion.substring(++index,index+1); } numStack.pushOne(Integer.valueOf(keepNum1)); } index++; } while (!operStack.isEmpty()){ oper = operStack.pop(); num1 = numStack.pop(); num2 = numStack.pop(); res = calcalator(num1,num2,oper); numStack.pushOne(res); } System.out.println(numStack.pop()); } /* * 比较操作符的优先级 * @author cjj_1 * @date 2020-08-06 11:50:31 * @param oper * @return **/ public static int priority(int oper){ if(oper == '*' || oper == '/') return 1; else if(oper == '+' || oper == '-') return 0; else return -1; } /* * 运算数据 * @author cjj_1 * @date 2020-08-06 11:51:24 * @param num1 * @param num2 * @param oper * @return **/ public static int calcalator(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: res=-1; break; } return res; } public static Boolean isOper(int oper){ return oper=='*' || oper=='/'||oper=='+'|| oper=='-'; } } /** * 栈 */ class Stack4Calcalator { int[] stack; int maxSize; int pop; public Stack4Calcalator(int maxsize){ this.pop = -1; this.maxSize = maxsize; this.stack = new int[maxsize]; } public boolean isFull() { if(pop == maxSize-1) return Boolean.TRUE; return Boolean.FALSE; } public boolean isEmpty() { if(pop == -1) return Boolean.TRUE; return Boolean.FALSE; } public void pushOne(int num){ if(isFull()){ return; } pop++; stack[pop]= num; } //出栈 public int pop(){ if(isEmpty()) return -1; return stack[pop--]; } //获取栈顶的值 public int picck(){ if(isEmpty()) return -1; return stack[pop]; } }

转载于:https://blog.csdn.net/weixin_40128696/article/details/107856835

最新回复(0)