基本原理:
利用栈的后进先出以及运算符优先级表。
判断几个情况:
1.如果不是运算符直接输出;
2.栈顶是左括号,在来的字符不是右括号的情况下直接入栈;
3.来的是右括号时,将栈内字符出栈病输出直到遇到左括号,左括号也出栈,但不入栈
4.来的运算符优先级低于栈顶运算符时,将栈顶运算符出栈直到栈顶运算符优先级低于新来的运算符,然后新来的入栈
5.最后,如果表达式遍历完了,将栈内所有元素输出
代码如下:
import java.io.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;
public class nbl {
public static void main(String[] args) throws IOException{
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(".//data.txt")));
String[] priority0 = reader.readLine().split(" ");
StringBuilder str = new StringBuilder(); //用来输出逆波兰式
LinkedList<String> priority = new LinkedList<>(Arrays.asList(priority0)); //记录运算符优先级
Scanner sc = new Scanner(System.in);
System.out.println("请输入表达式(符号之间请用空格隔开):");
String[] equ = sc.nextLine().split(" "); //使用字符串数组存放表达式
sc.close();
LinkedList<String> stack = new LinkedList<>(); //用来模拟栈
for (String s : equ) {
if (!priority.contains(s))
str.append(s);
else {
if (stack.isEmpty() || stack.getLast().equals("(") || (priority.indexOf(s) > priority.indexOf(stack.getLast()) && !s.equals(")")))
stack.addLast(s);
else if (s.equals(")")) {
while (!stack.getLast().equals("("))
str.append(stack.removeLast());
stack.removeLast();
} else {
while (!stack.isEmpty() && (priority.indexOf(s) < priority.indexOf(stack.getLast())) && !stack.getLast().equals("(") && !stack.getLast().equals(")")) {
str.append(stack.removeLast());
}
stack.addLast(s);
}
}
}
while (!stack.isEmpty()) {
str.append(stack.removeLast());
}
System.out.println("逆波兰式为:" + str.toString());
}
}