为啥要转换?
由于我们日常生活中,进行数值计算的话用的都是中缀表达式(1+2)。而计算机在进行运算时,由于其内存结构是栈式结构,所以后缀表达式(12+)是最适合计算机的。
转换思路如下:
需要说明的是,这个转换算法是前人想出来的,我们学习并理解的目的就是灵活运用来帮助我们解决问题。当然,也可以自己想算法,想出来就可以拿你名字命名了。😎
这个方法整体分为几个模块:
1、将中缀表达式转成对应的List
输入:s = “1+((2+3)×4)-5”
public static List<String> toInfixExpressionList(String s) {
// 定义一个List,存放中缀表达式对应的内容
List<String> ls = new ArrayList<String>();
int i = 0;// 这是一个指针,用于遍历 中缀表达式字符串
String str;// 对多位数的拼接
char c;// 每遍历到一个字符,就放到c
do {
// 如果c 是一个非数字,就需要加入到ls
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {// 0的ASCLL码为48,9的为57
ls.add("" + c);
i++;// i需要后移
} else {// 如果是一个数,需要考虑多位数问题
str = "";// 先将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;// 返回List
}
得到结果为:[1, +, (, (, 2, +, 3, ), ×, 4, ), -, 5]
2、将得到的中缀表达式对应的List => 后缀表达式对应的List
即:[1,+,(,(,2,+,3,),×,4,),-,5] => [1,2,3,+,4,×,+,5,-]
public static List<String> parseSuffixExpressionList(List<String> ls) {
// 定义两个栈
Stack<String> s1 = new Stack<String>();// 符号栈
// 说明:s2这个栈,在整个转换过程中,没有pop操作,而且后面还需要逆序输出,因此比较麻烦。
// 这里就不用Stack<String> 直接使用List<String> s2
// Stack<String> s2 = new Stack<String>();//储存中间结果的栈s2
List<String> s2 = new ArrayList<String>();// 储存中间结果的栈s2
// 遍历ls
for (String item : ls) {
// 如果是一个数,加入到s2
if (item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
// 如果是右括号")",则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
while (!s1.peek().equals("(")) {
s2.add(s1.pop());// 把s1栈顶的元素弹出,加入s2
}
s1.pop();// !!!!!!!!!!将 ( 弹出s1栈,消除小括号
} else {
// 当item的优先级,小于等于栈顶运算符,将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较
// 问题:缺少一个比较优先级高低的方法
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
// 还需要将item 压入栈
s1.push(item);
}
}
// 将s1 中剩余的运算符依次弹出并加入 s2
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;// 注意因为是存放到List(是有序的),因此按顺序输出就是对应的后缀表达式对应的List
}
完整代码如下:
package com.huey.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
//这里导List包,有两个选项,这个java.awt.List;导入会报错。
/**
* @author Huey 2021年2月3日下午7:44:27
*
*/
public class PolandNotation {
public static void main(String[] args) {
// 完成将一个中缀表达式转成后缀表达式的功能
// 说明
// 1、1+((2+3)×4)-5 => 1 2 3 + 4 × + 5 -
// 2、因为直接对str 进行操作,不方便,因此先将"1+((2+3)×4)-5" => 中缀的表达式对应的List
// 即"1+((2+3)×4)-5" => ArrayList[1,+,(,(,2,+,3,),×,4,),-,5]
// 3、将得到的中缀表达式对应的List => 后缀表达式对应的List
// 即ArrayList[1,+,(,(,2,+,3,),×,4,),-,5] => ArrayList[1,2,3,+,4,×,+,5,-]
String expression = "1+((2+3)×4)-5";
List<String> infixExpressionList = toInfixExpressionList(expression);
System.out.println("中缀表达式对应的List" + infixExpressionList);// [1, +, (, (, 2, +, 3, ), ×, 4, ), -, 5]
List<String> suffixExpressionList = parseSuffixExpressionList(infixExpressionList);// 返回一个后缀表达式对应的List
System.out.println("后缀表达式对应的List" + suffixExpressionList);
System.out.printf("expression=%d", calculate(suffixExpressionList));
/*
* 先定义一个逆波兰表达式 (3+4)×5-6 => 3 4 + 5 × 6 - => 29 4×5-8+60+8/2 => 4 5 × 8 - 60 + 8
* 2 / + 为了方便,逆波兰表达式的数字 和符号用括号隔开 String suffixExpression =
* "34 4 + 5 × 6 -";//184 String suffixExpression = "4 5 × 8 - 60 + 8 2 / +";//
* 76
*
* 思路 1、先将suffixExpression 放到ArrayList中 2、将ArrayList 传递给一个方法,遍历ArrayList 配合栈完成计算
*
* List<String> listString = getListString(suffixExpression);// Alt+Shift+L
* System.out.println("listString=" + listString);// 将后缀表达式分割后的结果 int res =
* calculate(listString); System.out.println("计算的结果是=" + res);
*/
}
// ArrayList[1,+,(,(,2,+,3,),×,4,),-,5] => ArrayList[1,2,3,+,4,×,+,5,-]
// 方法:将得到的中缀表达式对应的List => 后缀表达式对应的List
public static List<String> parseSuffixExpressionList(List<String> ls) {
// 定义两个栈
Stack<String> s1 = new Stack<String>();// 符号栈
// 说明:s2这个栈,在整个转换过程中,没有pop操作,而且后面还需要逆序输出,因此比较麻烦。
// 这里就不用Stack<String> 直接使用List<String> s2
// Stack<String> s2 = new Stack<String>();//储存中间结果的栈s2
List<String> s2 = new ArrayList<String>();// 储存中间结果的栈s2
// 遍历ls
for (String item : ls) {
// 如果是一个数,加入到s2
if (item.matches("\\d+")) {
s2.add(item);
} else if (item.equals("(")) {
s1.push(item);
} else if (item.equals(")")) {
// 如果是右括号")",则依次弹出s1栈顶的运算符,并压入s2,直到遇到左括号为止,此时将这一对括号丢弃
while (!s1.peek().equals("(")) {
s2.add(s1.pop());// 把s1栈顶的元素弹出,加入s2
}
s1.pop();// !!!!!!!!!!将 ( 弹出s1栈,消除小括号
} else {
// 当item的优先级,小于等于栈顶运算符,将s1栈顶的运算符弹出并加入到s2中,再次转到(4.1)与s1中新的栈顶运算符相比较
// 问题:缺少一个比较优先级高低的方法
while (s1.size() != 0 && Operation.getValue(s1.peek()) >= Operation.getValue(item)) {
s2.add(s1.pop());
}
// 还需要将item 压入栈
s1.push(item);
}
}
// 将s1 中剩余的运算符依次弹出并加入 s2
while (s1.size() != 0) {
s2.add(s1.pop());
}
return s2;// 注意因为是存放到List(是有序的),因此按顺序输出就是对应的后缀表达式对应的List
}
// 方法:将中缀表达式转成对应的List
// s = "1+((2+3)×4)-5"
public static List<String> toInfixExpressionList(String s) {
// 定义一个List,存放中缀表达式对应的内容
List<String> ls = new ArrayList<String>();
int i = 0;// 这是一个指针,用于遍历 中缀表达式字符串
String str;// 对多位数的拼接
char c;// 每遍历到一个字符,就放到c
do {
// 如果c 是一个非数字,就需要加入到ls
if ((c = s.charAt(i)) < 48 || (c = s.charAt(i)) > 57) {// 0的ASCLL码为48,9的为57
ls.add("" + c);
i++;// i需要后移
} else {// 如果是一个数,需要考虑多位数问题
str = "";// 先将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;// 返回List
}
// 一个逆波兰表达式,依次将数据和运算符 放入到ArrayList 中
public static List<String> getListString(String suffixExpression) {
// 将suffixExpression 分割
String[] split = suffixExpression.split(" ");// 以空格为标志,对字符串分割
List<String> list = new ArrayList<String>();// 创建空的list,存放下面通过for 循环,分割之后的结果。
// 分割完后就成为一个数组了,每循环一次就取出一个元素
for (String ele : split) {
list.add(ele);
}
return list;
}
public static int calculate(List<String> ls) {
// 创建栈,只需要一个栈即可
Stack<String> stack = new Stack<String>();
// 遍历 ls
for (String item : ls) {
// 这里使用 正则表达式 来取出数
if (item.matches("\\d+")) {// 匹配的是多位数
// 入栈
stack.push(item);
} else {
// pop 出两个数,并运算,再入栈
int num2 = Integer.parseInt(stack.pop());// 将字符串类型的数字,转成int 类型的数
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("运算符有误");
}
// 把res 入栈
stack.push("" + res);// 把整数转为字符串
}
}
// 最后留在stack 中的数据就是运算结果
return Integer.parseInt(stack.pop());
}
}
//编写一个类Operation 可以返回一个运算符 对应的优先级
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("不存在该运算符~");
break;
}
return result;
}
}
测试: