分析步骤如下:
- 初始化两个栈:运算符栈s1和存储中间结果的栈s2
- 从左至右扫描中缀表达式
- 遇到操作数时,将其压入s2
- 遇到运算符时,比较其与s1栈顶运算符的优先级
4.1 如果s1为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
4.2 否则,若优先级比栈顶运算符高,也将运算符压入栈s2
4.3 否则,将s1栈顶运算符弹出并加入到s2中,再次转到4.1 与s1中新的栈顶运算符相比较. - 遇到括号时:
5.1 如果是左括号“(”,则直接压入s1
5.2 如果是又括号“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将一对左括号丢弃。 - 重复上述步骤,直到表达式的最右边
- 将s1中剩余的运算符依次弹出并压入s2
- 依次弹出s2中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式
代码实现如下:
/**
* @Author: wy
* @ProjectName: LFH
* @Package: com.feel.algorithm.java
* @Description: 将中缀表达式转为后缀表达式
* @Date: Created in 11:26 2019/7/1
*/
public class PolandNotation {
public static void main(String[] args) {
String exp = "1+((2+3)*4)-5";
List<String> list = toInfixExp(exp);
System.out.println(list);
List<String> parseList = parseSuffixExp(list);
System.out.println("后缀表达式" + parseList);
}
/**
* 将得到的中缀表达式对应的list => 后缀表达式对饮的list
*
* @param list
* @return
*/
public static List<String> parseSuffixExp(List<String> list) {
/*初始化两个栈*/
Stack<String> s1 = new Stack<String>();
//Stack<String> s2=new Stack<>();
List<String> s2 = new ArrayList<>();
for (String item : list) {
if (item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
while (!s1.peek().equals("(")) {
s2.add(s1.pop());
}
/*左小括号弹栈*/
s1.pop();
} else {
/*当item的优先级小于等于s1栈顶运算符时,将
* s1栈顶运算符弹出并加入到s2中,再次与s1栈顶元素比较
*/
while (s1.size() != 0 && Priority.getValue(item) <= Priority.getValue(s1.peek())) {
s2.add(s1.pop());
}
/*将item压入栈中*/
s1.push(item);
}
}
/*将s1中剩余运算符依次加入到s2中*/
while (s1.size() != 0) {
s2.add(s1.pop());
}
/*因为是存放到list中,因此按顺序输出就是得到的逆波兰表达式*/
return s2;
}
/**
* 将中缀表达式转为对应的List
*
* @param s
* @return
*/
public static List<String> toInfixExp(String s) {
List<String> list = new ArrayList<>();
/*用于遍历中缀字符串的指针*/
int i = 0;
/*对多位数进行拼接*/
String str;
/*每遍历一个字符,放入到c*/
char c;
do {
/*如果这是一个非数字,需要加到list中*/
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
list.add("" + c);
i++;
}
/*如果是一个数字,要考虑多位数*/
else {
/*先将str置空*/
str = "";
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
str += c;
i++;
}
list.add(str);
}
} while (i < s.length());
return list;
}
}
class Priority {
private static int ADD = 1;
private static int SUB = 1;
private static int MUL = 2;
private static int DIV = 2;
public static int getValue(String s) {
int result = 0;
switch (s) {
case "+":
result = ADD;
case "-":
result = SUB;
case "*":
result = MUL;
case "/":
result = DIV;
default:
//System.out.println("无此操作符");
break;
}
return result;
}
}