import java.util.Stack;
public class 栈的表达式计算 {
public static void main(String[] args) {
Stack<Integer> number = new Stack<Integer>();
Stack<Character> fuhao = new Stack<Character>();
String ex = "77*2+3+4+10/5";
int index = 0;
int num1 = 0;
int num2 = 0;
char c = ' ';
while (true) {
// 字符
char op = ex.charAt(index);
if (isoper(op) == true) {
//符号栈不为空
if (!fuhao.isEmpty()) {
//如果当前运算符的优先级小于或等于运算符中的优先级,则从符号栈中
//取出一个运算符,再从数栈中弹出两个数进行计算,并将计算后的结果,再压入数栈
if (youxianji(op) <= youxianji(fuhao.peek())) {
num2 = number.pop();
num1 = number.pop();
c = fuhao.pop();
number.push(cul(num1, num2, c));
fuhao.push(op);
} else {
//符号栈为空,直接入栈
fuhao.push(op);
}
} else {
//如果当前运算符的优先级大于运算符中的优先级,直接入栈
fuhao.push(op);
}
index ++;
}
// 数字
else {
String num = "";
//解决数字是多位数的情况
while (!isoper((ex.charAt(index)))) {
num = num + (ex.charAt(index)-48);
index = index + 1;
//为了处理表达式最末尾的情况,到末尾后已经没有操作数了,终止循环
if (index>=ex.length()) {
break;
}
}
//数字入栈
number.push(Integer.parseInt(num));
}
if (index>=ex.length()) {
break;
}
}
while(true){
if (fuhao.isEmpty()) {
break;
} else {
num2 = number.pop();
num1 = number.pop();
c = fuhao.pop();
number.push(cul(num1, num2, c));
}
}
System.out.println(number.peek());
}
public static boolean isoper(int i) {
if (i == '+' || i == '-' || i == '*' || i == '/') {
return true;
} else {
return false;
}
}
// 判断优先级
public static int youxianji(char c) {
if (c == '*' || c == '/') {
return 1;
} else if (c == '+' || c == '-') {
return 0;
} else {
return -1;
}
}
public static int cul(int num1, int num2, char c) {
int res = 0;
switch (c) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
break;
}
return res;
}
}
java数据结构之表达式计算
最新推荐文章于 2023-07-21 19:41:24 发布