java实现中缀表达式转后缀表达式
时间: 2023-10-23 18:11:40 浏览: 83
好的,以下是 Java 实现中缀表达式转后缀表达式的代码:
```java
import java.util.Stack;
public class InfixToPostfix {
public static int precedence(char ch) {
switch (ch) {
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
public static String infixToPostfix(String expression) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < expression.length(); i++) {
char ch = expression.charAt(i);
if (Character.isLetterOrDigit(ch)) {
result.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
if (!stack.isEmpty() && stack.peek() != '(') {
return "Invalid Expression";
} else {
stack.pop();
}
} else {
while (!stack.isEmpty() && precedence(ch) <= precedence(stack.peek())) {
result.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
public static void main(String[] args) {
String expression = "a+b*(c^d-e)^(f+g*h)-i";
System.out.println(infixToPostfix(expression));
}
}
```
阅读全文