一、中缀表达式转后缀表达式
思路:1)将中缀表达式存储到一个List当中
2)将中缀表达式List转成后缀表达式对应的List
1)代码实现
//将中缀表达式装到List当中
public static List<String> toInfixList(String infix){
List<String> infixList = new ArrayList<String>();
int i = 0;//指针,用于遍历中缀字符串
String str = "";//用于多位数的拼接
char ch;//用于存放遍历出来的每一个字符
do{
//如果c是一个非数字,直接添加到List中,数字在阿斯卡码表中的区间是48[0]到57[9]
if((ch=infix.charAt(i)) < 48 || (ch=infix.charAt(i)) > 57){
infixList.add(ch+"");
i++;
}else{//如果为数字,要考虑到多位数的问题,进行字符串的拼接
str = "";//每次进行多位数拼接之前要将上一次拼接的多位数置空
while(i < infix.length() && (ch=infix.charAt(i)) >= 48 && (ch=infix.charAt(i)) <= 57){
str += ch;
i++;
}
infixList.add(str);
}
}while(i < infix.length());
return infixList;
}
2)代码实现
![5a6838eec0beb1d3a801a28e6a56701a.png](https://i-blog.csdnimg.cn/blog_migrate/0ec78553261f7db387082260a4ebab24.jpeg)
//将中缀表达式List转成后缀表达式对应的List:思路用栈说明,代码使用List实现
public static List<String> toSuffixList(List<String> infixList){
Stack<String> s1 = new Stack<String>();//符号栈
/**
* 因为在中缀转后缀的过程中,s2至始至终都在存放东西,而没有pop的操作,
* 并且在后期还需要逆序进行运算,可以使用List替代较为方便
* */
List<String> s2 = new ArrayList<String>();
for(String item:infixList){
//如果是一个数,则加入s2
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.getPriority(s1.peek()) >= Operation.getPriority(item)){
s2.add(s1.pop());
}
//还需要将item压入栈中
s1.push(item);
}
}
//将s1中剩余的元素加入到s2中
while(s1.size() != 0){
s2.add(s1.pop());
}
return s2;
}
二、后缀表达式的计算
![2bf7b74eca6bf5da7375abbbed708609.png](https://i-blog.csdnimg.cn/blog_migrate/4736422bcb50184081f6e21f819d1d73.jpeg)
//传入一个List,返回一个结果
/**
* 思路:遍历list,如果是数字则压入栈中,如果是操作符则pop出两个数字,运算结果压入栈中
* */
public static int cal(List<String> ls){
Stack<String> stack = new Stack<String>();//注意是存储字符串的栈
//遍历ls
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;
switch (item) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "*":
res = num1 * num2;
break;
case "/":
res = num1 / num2;
break;
default:
break;
}
stack.push(res+"");//将结果类型转成字符串
}
}
return Integer.parseInt(stack.pop());
}
}