中缀转后缀
1、初始化两个栈:运算符栈是s1和存储中间结果的栈s2;
2、从左至右扫描中缀表达式;
3、遇到操作数,将其压入s2;
4、遇到运算符时,比较与s1栈顶运算符的优先级;
4.1)如果s1为空,则直接压入s1;
4.2)否则,若优先级比栈顶元素高,也压入s1;
4.3)否则,将s1运算符弹出并压入s2中,再次转4.1)与s1中新的运算符比较
5、遇到括号时候:
5.1)如果是“(”,直接压入s1;
5.2)如果是“)”,则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
6、重复2-5,直到表达式的最右边
7、将s1中剩余的运算符依次弹出并压入s2
8、依次弹出s2的元素并输出,结果的逆序即为中缀表达式的后缀表达式
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
String suffixExpression = "(1+2)/3";
List<String> num = toInfixExpressionList(suffixExpression);
List<String> num1 = parseSuffixExpressionList(num);
System.out.println("中缀:" + num);
System.out.println("后缀:" + num1);
System.out.println("运算结果:" + calculate(num1));
}
public static List<String> toInfixExpressionList(String s) {
List<String> ls = new ArrayList<String>();
int i = 0;
String str;
char c;
do {
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {
ls.add("" + c);
i++;
} else {
str = "";
while (i < s.length() && (c = s.charAt(i)) >= 48 && (c = s.charAt(i)) <= 57) {
str += c;
i++;
}
ls.add(str);
}
} while (i < s.length());
return ls;
}
public static List<String> parseSuffixExpressionList(List<String> ls) {
Stack<String> s1 = new Stack<>();
List<String> s2 = new ArrayList<>();
for (String item : ls) {
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 {
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
s1.push(item);
}
}
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;
}
public static int calculate(List<String> ls) {
Stack<String> stack = new Stack<String>();
for (String item : ls) {
if (item.matches("\\d+")) {
stack.push(item);
} else {
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")) {
res = num1 + num2;
} else if (item.equals("-")) {
res = num1 - num2;
} else if (item.equals("*")) {
res = num1 * num2;
} else if (item.equals("/")) {
res = num1 / num2;
} else {
throw new RuntimeException("运算符问题");
}
stack.push(res + "");
}
}
return Integer.parseInt(stack.pop());
}
}
class Operation {
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 operation) {
int result = 0;
switch (operation) {
case "+":
result = ADD;
break;
case "-":
result = SUB;
break;
case "*":
result = MUL;
break;
case "/":
result = DIV;
break;
default:
System.out.println("不存在该比较" + operation);
break;
}
return result;
}
}