中缀表达式求值:
遍历表达式
1、如果是数字,直接入数栈
2、如果是符号:
(1)如果符号栈为空,直接入栈。
(2)如果符号栈不为空:
1)如果当前运算符的优先级小于等于符号栈中的操作符,需要从数栈中pop出两个数字,在符号栈中pop出一个符号,进行运算,将运算 结果压入数栈,并将当前操作符压入符号栈。
2)如果当前操作符优先级大于栈中操作符,直接入符号栈。
3、扫描完毕,顺序的从数栈和符号栈中pop相应的数字和符号进行计算,并将运算结果压入数栈。
4、最后数栈中只有一个数字,便是表达式的运算结果。
public class CalculatorStack {
private int maxSize;
private int[] stack;
private int top = -1;
public CalculatorStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[maxSize];
}
// 栈是否为空
public boolean isEmpty() {
return top == -1;
}
// 栈是否满
public boolean isFull() {
return top == (maxSize - 1);
}
// 入栈
public void push(int n) {
if (isFull()) {
throw new RuntimeException("栈已满");
}
stack[++top] = n;
}
// 出栈
public int pop() {
if (isEmpty()) {
throw new RuntimeException("栈为空");
}
return stack[top--];
}
// 返回运算符的优先级,使用数字表示,数字越大,优先级越高
public int priority(int op) {
if (op == '*' || op == '/') {
return 1;
}
if (op == '+' || op == '-') {
return 0;
}
else
return -1;
}
// 判断是不是运算符
public boolean isOp(char val) {
return val == '+' || val == '-' || val == '*' || val == '/';
}
// 查看栈顶元素
public int getTopValue() {
return stack[top];
}
// 计算
public int cal(int num1, int num2, int op) {
return switch (op) {
case '+' -> num1 + num2;
case '-' -> num2 - num1;
case '*' -> num1 * num2;
case '/' -> num2 / num1;
default -> 0;
};
}
}
public static void main(String[] args) {
String expression = "7*2*2-5+1-5+3-4";
CalculatorStack numStack = new CalculatorStack(10);
CalculatorStack opStack = new CalculatorStack(10);
int num1 = 0;
int num2 = 0;
int op = 0;
int index = 0;
char ch = ' ';
String tmp = "";
while (index < expression.length()) {
ch = expression.substring(index, index + 1).charAt(0);
if (opStack.isOp(ch)) {
if (!opStack.isEmpty()) {
if (opStack.priority(ch) <= opStack.priority(opStack.getTopValue())) {
num1 = numStack.pop();
num2 = numStack.pop();
op = opStack.pop();
numStack.push(numStack.cal(num1, num2, op));
}
}
opStack.push(ch);
} else {
// 多位数处理
tmp += ch;
if (index == (expression.length() - 1)) {
numStack.push(Integer.parseInt(tmp));
} else {
if (opStack.isOp(expression.substring(index + 1, index + 2).charAt(0))) {
numStack.push(Integer.parseInt(tmp));
tmp = "";
}
}
}
index++;
}
while (!opStack.isEmpty()) {
num1 = numStack.pop();
num2 = numStack.pop();
op = opStack.pop();
numStack.push(numStack.cal(num1, num2, op));
}
System.out.println(expression + '=' + numStack.pop());
}
}