输入中缀表达式并将其转化为后缀表达式,输出结果,写出java代码
时间: 2024-05-03 21:20:56 浏览: 78
好的,以下是将中缀表达式转化为后缀表达式的Java代码:
```java
import java.util.Stack;
public class InfixToPostfix {
public static String infixToPostfix(String expression) {
String result = ""; // 存储结果的字符串
Stack<Character> operatorStack = new Stack<>(); // 运算符栈
for (int i = 0; i < expression.length(); i++) {
char c = expression.charAt(i);
if (Character.isDigit(c)) {
// 如果字符是数字则直接添加到结果中
result += c;
} else if (c == '+' || c == '-' || c == '*' || c == '/') {
// 如果字符是运算符
// 如果运算符栈为空则直接入栈
if (operatorStack.isEmpty()) {
operatorStack.push(c);
} else {
// 如果栈不为空则判断优先级
char topOperator = operatorStack.peek();
while (!operatorStack.isEmpty() && precedence(topOperator) >= precedence(c)) {
result += operatorStack.pop();
if (!operatorStack.isEmpty()) {
topOperator = operatorStack.peek();
}
}
operatorStack.push(c); // 将当前运算符入栈
}
} else if (c == '(') {
// 如果是左括号则直接入栈
operatorStack.push(c);
} else if (c == ')') {
// 如果是右括号则将运算符栈中的运算符全部出栈到结果中
char topOperator = operatorStack.pop();
while (topOperator != '(') {
result += topOperator;
if
阅读全文