完整代码如下:
package com.wqc.stack;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author 高瞻远瞩
* @version 1.0
* @motto 算法并不可怕, 可怕的是你不敢面对它, 加油!别浮躁~冲击大厂!!!
* 演示逆波兰表达式(后缀表达式)的计算过程 并演示中缀表达式转后缀表达式
* (30+4)*5-6 对应的后缀表达式 是 30 4 + 5 * 6 - ==》164
* 4 * 5 - 8 + 60 + 8 / 2 对应的后缀表达式==> 4 5 * 8 - 60 + 8 2 / + 计算结果==》76
* 总结 :一句话 ! 正则表达式牛逼!!! 集合牛逼!!!
*/
public class PolandNotation {
public static void main(String[] args) {
/**
* 以下是将一个中缀表达式转换成一个后缀表达式的实现过程
*/
// String infixExpression = "( 30 + 4 ) * 5 - 6";
// String infixExpression = "4 * 5 - 8 + 60 + 8 / 2";
String infixExpression = "1+((2+3)*4)-5";
// ArrayList<String> list = stringConvertList(infixExpression);
ArrayList<String> list = (ArrayList<String>) infillConvertList(infixExpression);
System.out.println("中缀表达式=" + list);
//初始化两个栈 一个用来存运算符和(左括号 另一个存数字和中间加进来的运算符 所以类型都定义为String
Stack<String> stack1 = new Stack<>();
//因为2栈在整个转换过程中 没有出栈操作 所以可以用一个ArrayList<String>集合替代这个栈
// 最后只需遍历这个集合 再进行依次拼接就是最后转换的逆波兰表达式
Stack<String> stack2 = new Stack<>();
//遍历集合 相当于扫描字符串
for (String s : list) {
if (s.matches("\\d+")) {//如果是一位数字或者多位数字的话 直接压2栈
stack2.push(" " + s);//再拼接上一个空格好区分是否是一个多位数
}
if ("(".equals(s)) {
stack1.push(s);
}
if (")".equals(s)) {//如果是右括号的话 依次弹出s1栈顶的运算符 并压入s2 直到遇到左括号为止 左右括号分别丢弃
// while (true) {
// String s1 = stack1.pop();//先弹栈 然后就进行判断
// if (s1.equals("(")) {
// break;
// }
// stack2.push(s1);
// }
//上面注释的另一种写法 只要它的1栈顶不是左括号 就进行弹栈加入到2栈
while (!stack1.peek().equals("(")) {
stack2.push(stack1.pop());
}
stack1.pop();//跳出循环说明栈顶元素为左括号 这时候最后需要将1栈的左括号弹出
}
if (s.matches("[+\\-*/]")) {//如果是运算符的话
// if (stack1.empty()) {//空的话 直接压入
// stack1.push(s);
// }else {
// //否则进行优先级判断
// if (priority(s.charAt(0)) > priority(stack1.peek().charAt(0))) {
// stack1.push(s);//优先级比栈顶的大的话 直接入栈
// } else {//如果比栈顶小的话 弹出栈顶元素 并压入2栈 并循环以上步骤 从空判断开始
// while (true) {//先进行弹出 并压入2栈 就开始循环进行判断 直到符合两个条件为止
// stack2.push(stack1.pop());
// if (stack1.empty()) {//空的话 直接压入
// stack1.push(s);
// break;
// }
// if (priority(s.charAt(0)) > priority(stack1.peek().charAt(0))) {
// stack1.push(s);//优先级比栈顶的大的话 直接入栈
// break;
// }
// }
// }
// }
//以上注释掉的代码 可以用下列几行代码代替
while (!stack1.empty() && operator.getPriority(s) <= operator.getPriority(stack1.peek())) {
stack2.push(stack1.pop());
}
stack1.push(s);//直到该值的优先级大于栈顶 就直接加入 否则一直进行如上while循环
}
}
//当遍历结束时 再把1栈中剩余的运算符压入2栈
while (true) {
//先判断栈1是否为null 如果为null 直接跳出循环
if (stack1.empty()) {
break;
}
//否则就依次进行弹栈操作 并把它压入2栈 直到栈1为空跳出循环
stack2.push(stack1.pop());
}
//此时依次弹出栈2里面的内容 就是我们想要的结果的逆序
String tempStr = "";//该字符串用于拼接弹出的内容
while (true) {
if (stack2.empty()) {
break;
}
tempStr += stack2.pop();
}
System.out.println(tempStr);
//然后将这个字符串进行反转 得到的就是最终的后缀表达式
String regStr = "\\d\\d*|[+\\-*/]";
Pattern pattern = Pattern.compile(regStr);
Matcher matcher = pattern.matcher(tempStr);
ArrayList<String> arrayList = new ArrayList<>();//用于存放用正则表达式找到的数字或者运算符
while (matcher.find()) {
arrayList.add(matcher.group(0));
}
//然后再将集合进行反转就得到后缀表达式 最后把后缀表达式用StringBuffer进行拼接
Collections.reverse(arrayList);
System.out.println("后缀表达式=" + arrayList);
StringBuffer stringBuffer = new StringBuffer();
String suffixExpression = "";
for (int i = 0; i < arrayList.size(); i++) {
stringBuffer.append(arrayList.get(i) + " ");
}
suffixExpression = stringBuffer.toString();
System.out.println("转换过后的后缀表达式=" + suffixExpression);
/**
* 以下代码是后缀表达式的计算过程的实现
*/
// String suffixExpression = "30 4 + 5 * 6 -";//也可以将分割的每一个字符串封装到一个ArrayList集合中
//把得到的后缀表达式用空格隔开 最后分割的时候可以区分多位数
Stack<Integer> numStack = new Stack<>();//初始化一个数栈
String[] split = suffixExpression.split(" ");
for (int i = 0; i < split.length; i++) {
String s = split[i];
if (s.matches("\\d+")) {//如果是数 直接压入栈中
numStack.push(Integer.parseInt(s));
}
if (s.matches("[+\\-*/]")) {//如果是操作符的话 数栈中弹两个 和操作符进行运算 把运算结果压入数栈
int i1 = numStack.pop();
int i2 = numStack.pop();
int value = cal(i1, i2, s.charAt(0));
numStack.push(value);
}
}
//当遍历结束 数栈中剩下的那个数就是计算出的最终结果
System.out.println("计算出后缀表达式的结果=" + numStack.pop());
}
//计算方法
public static int cal(int n1, int n2, int operator) {
if (operator == '+') {
return n1 + n2;
} else if (operator == '-') {
return n2 - n1; //把后弹出的数作为减数
} else if (operator == '*') {
return n1 * n2;
} else if (operator == '/') {
return n2 / n1;//后弹的数作为除数
}
throw new RuntimeException();
}
//判断一个操作符的优先级 假定*/的有限级一样 都是1
//+-的优先级一样 都是0 如果输入其他的 返回-1 数值越大 优先级越高
public static int priority(int operator) {//char类型的可以用数字来比较
if (operator == '*' || operator == '/') {
return 1;
} else if (operator == '+' || operator == '-') {
return 0;
}
return -1;
}
//该方法将一个字符串进行分割 然后分别封装到ArrayList集合中进行返回
public static ArrayList<String> stringConvertList(String str) {
String[] s = str.split(" ");
ArrayList<String> list = new ArrayList<>();
for (String s1 : s) {
list.add(s1);
}
return list;
}
//写一个方法 将中缀表达式转换成一个list返回
public static List<String> infillConvertList(String str) {
List<String> al = new ArrayList<>();
int i = 0;
char c;
String connectStr = "";
while (true) {
if (i == str.length()) {
break;
}
//如果是非数字的话 直接加入集合即可
if ((c = str.charAt(i)) < 48 || (c = str.charAt(i)) > 57) {
al.add(str.charAt(i) + "");
i++;
} else {
connectStr = "";//再次进入else时 必须要将将这个串置空
while (true) {
if (i == str.length() || (c = str.charAt(i)) < 48 || (c = str.charAt(i)) > 57) {
break; //只要一个条件满足就跳出循环 不满足数字的话 或者长度=字符串的长度
//都不满足条件就进行拼接 这个while循环也起到了遍历的效果 和外边的那个while循环相互协作
}
connectStr += c;
i++;
}
al.add(connectStr);
}
}
return al;
}
}
//该类返回一个对应的优先级
class operator {
private static int add = 1;
private static int minus = 1;
private static int mul = 2;
private static int div = 2;
//根据传入的操作符 返回对应的优先级
public static int getPriority(String ope) {
int result = 0;
switch (ope) {
case "+":
result = add;
break;
case "-":
result = minus;
break;
case "*":
result = mul;
break;
case "/":
result = div;
break;
default:
System.out.println("获取优先级失败...");
break;
}
return result;
}
}