publicintpop(){ if (isEmpty()) { System.out.println("栈为空"); return -1; } int value = stack[top]; top--; return value; }
publicvoidlistShow(){ if (isEmpty()) { return; } //栈从顶部遍历,从top减一开始遍历 for (int i = top - 1; i >= 0; i--) { System.out.printf("stack[%d]=%d\n", i, stack[i]); } }
privateintlistStr(String str, StackManger numStack, StackManger operatorStack){ char[] charArray = str.toCharArray(); //主要用来拼接多位数字 StringBuilder strNum = new StringBuilder(); for (int index = 0; index < charArray.length; index++) { //判断是否为数字 if (!isOperator(charArray[index])) { strNum.append(charArray[index]); //当index为最后一位的时候,就不需要判断下一位是否是运算符 if (index == charArray.length - 1) { // numStack.push(Integer.parseInt(strNum)); //数字添加到数字栈中,不能直接存 因为存的不是 1 而是'1' 中间间隔48(或者直接 - '0') numStack.push(charArray[index] - '0'); } else { //判断下一位是否是不是数字,是的话继续扫描,是运算符就入栈 if (operatorStack.isOperator(charArray[index + 1])) { numStack.push(Integer.parseInt(strNum.toString())); //这里很重要,入栈之后进行清空 strNum = "1" 不清空将会一直往后面拼接 strNum = new StringBuilder();
} } } else { if (operatorStack.isEmpty()) { //如果符号栈为空,直接入栈 operatorStack.push(charArray[index]); //代表当前的运算符优先级小于或者等于栈中的运算符 } elseif (this.priority(charArray[index]) <= operatorStack.priority(operatorStack.peek())) { //不为空并且优先级低,则pop出一个符号和pop出两个数字进行运算 int num1 = numStack.pop(); int num2 = numStack.pop(); int operator = operatorStack.pop(); //得到运算结果 int res = this.calc(num1, num2, operator); //将运算结果压入数栈中 numStack.push(res); //将当前运算符入符号栈 operatorStack.push(charArray[index]); } elseif (this.priority(charArray[index]) > operatorStack.priority(operatorStack.peek())) { //将运算符直接压栈 operatorStack.push(charArray[index]); } } }
while (!operatorStack.isEmpty()) { //运算到最后符号栈为空 //当表达式扫描完毕,就顺序的从数栈和符号栈pop进行运算 int num1 = numStack.pop(); int num2 = numStack.pop(); int operator = operatorStack.pop(); int res = this.calc(num1, num2, operator); numStack.push(res);
//主要存放运算符 StackManger operatorStack = new StackManger(10); StackManger stackManger = new StackManger(); int res = stackManger.listStr(str, numStack, operatorStack); System.out.println("运算的结果为:" + res);