请用Java写准波兰变换,使用户输入的中缀表达式,输出后缀表达式
时间: 2023-07-07 09:22:08 浏览: 85
java实现逆波兰计算器,输入中缀表达式可以得到后缀表达式,并且计算这个后缀表达式的值, 且输入的表达式只要正确即可运行
以下是使用Java实现准波兰变换,将中缀表达式转换为后缀表达式的代码:
```java
import java.util.*;
public class QFT {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("请输入中缀表达式:");
String infix = sc.nextLine();
String postfix = infixToPostfix(infix);
System.out.println("后缀表达式为:" + postfix);
}
//中缀表达式转后缀表达式
public static String infixToPostfix(String infix) {
StringBuilder postfix = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
if (ch == ' ') {
continue;
} else if (Character.isDigit(ch)) {
postfix.append(ch);
while (i + 1 < infix.length() && Character.isDigit(infix.charAt(i + 1))) {
i++;
postfix.append(infix.charAt(i));
}
postfix.append(" ");
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
postfix.append(stack.pop() + " ");
}
stack.pop();
} else {
while (!stack.isEmpty() && getPriority(ch) <= getPriority(stack.peek())) {
postfix.append(stack.pop() + " ");
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
postfix.append(stack.pop() + " ");
}
return postfix.toString();
}
//获取运算符优先级
public static int getPriority(char ch) {
if (ch == '+' || ch == '-') {
return 1;
} else if (ch == '*' || ch == '/') {
return 2;
} else if (ch == '^') {
return 3;
} else {
return 0;
}
}
}
```
使用示例:
输入:`(1+2)*3-4/5`
输出:`12+3*45/-`
阅读全文