容器栈
/** * 数组表示栈 */ public class CalArrayStack { //栈的大小 private int maxSize; //数组 private int[] stack; // 栈顶 private int top = -1; public CalArrayStack(int maxSize) { this.maxSize = maxSize; stack = new int[maxSize]; } // 栈满 public boolean isFull() { return top == maxSize - 1; } // 栈空 public boolean isEmpty() { return top == -1; } public void push(int num) { if (isFull()) { return; } top++; stack[top] = num; } public int pop() { if (isEmpty()) { throw new RuntimeException("栈数据为空"); } int res = stack[top]; top--; return res; } public int peek() { return stack[top]; } //遍历栈 public void list() { if (isEmpty()) { return; } for (int i = top; i >= 0; i--) { System.out.println(stack[i]); } } /** * 返回运算符的优先级,优先级使用数字表示 * 数字越大,优先级越高; */ public static int priority(int oper) { if (oper == '*' || oper == '/') { return 1; } else if (oper == '+' || oper == '-') { return 0; } else { return -1; } } // 判断是不是一个运算符 public static boolean isOper(char val) { return val == '*' || val == '/' || val == '+' || val == '-'; } //计算方法 public static 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; } }
计算并测试
public class Calculator { public static void main(String[] args) { //初始化表达式 String expression = "7*2*2-5+1-5+3-4"; int num = getCal(expression); System.out.println(num); } private static int getCal(String expression) { // 创建数字栈 CalArrayStack numStack = new CalArrayStack(10); // 创建操作符栈 CalArrayStack operStack = new CalArrayStack(10); // 定义需要的变量 int index = 0; int num1 = 0; int num2 = 0; int oper = 0; int res = 0; String keepNum = ""; //将每次扫描到的插入保存到ch char ch = ' '; // 开始遍历表达式 while (true) { ch = expression.charAt(index); boolean isOper = CalArrayStack.isOper(ch); if (isOper) { if (operStack.isEmpty()) { operStack.push(ch); } else { int peek = operStack.peek(); if (CalArrayStack.priority(ch) > CalArrayStack.priority(peek)) { operStack.push(ch); } else { num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = CalArrayStack.cal(num1, num2, oper); numStack.push(res); operStack.push(ch); } } } else { keepNum += ch; //处理多位数 while ((index + 1) < expression.length()) { ch = expression.charAt(index + 1); if (!CalArrayStack.isOper(ch)) { index++; keepNum += ch; } else { break; } } numStack.push(Integer.valueOf(keepNum.toString())); keepNum = ""; } index++; if (index == expression.length()) { break; } } while (!operStack.isEmpty()) { num1 = numStack.pop(); num2 = numStack.pop(); oper = operStack.pop(); res = CalArrayStack.cal(num1, num2, oper); numStack.push(res); } return numStack.pop(); } }
18