代码思路如下✨✨✨✨
![](https://i-blog.csdnimg.cn/blog_migrate/4180bb4c6b4548e963cdeb073a8eb982.png)
package DataStructure;
import java.util.List;
import java.util.ArrayList;
import java.util.Stack;
/**
* Created with IntelliJ IDEA.
* Description:
* User: 86178
* Date: 2024-02-26
* Time: 11:17
*/
public class PolandExpression1 {
public static void main(String[] args) {
String s1="1+((2+3)*4)-5";
List<String> ss=toInfixExpression(s1);
System.out.println("后缀表达式是"+Transition(ss));
System.out.println("运算结果是"+PolandNotation.calculate(Transition(ss)));
}
//todo 先将字符串转换为字符数组 ArrayList[]
public static List<String> toInfixExpression(String s){
//定义一个List 存放数据
List<String> ls=new ArrayList<String>();
String str="";
int i=0;
do{
//todo 如果是操作符 直接加入字符数组
if(s.charAt(i)<48 || s.charAt(i)>57){
ls.add(""+s.charAt(i));
i++;
}
//todo 如果是数字 考虑多位数
else{
str="";
while(i<s.length() && s.charAt(i)>=48 && s.charAt(i)<=57){
str+=s.charAt(i);
i++;
}
ls.add(str);
}
}while(i<s.length());
return ls;
}
public static List<String> Transition(List<String> str){
//todo 将中缀表达式的List 转换为后缀
List<String> ret=new ArrayList<String>();
//定义两个栈
Stack<String> oper=new Stack<String>();
//todo 因为ans在整个操作中没有弹栈操作 直接使用List<String> ans
//Stack<String> ans=new Stack<String>();
List<String> ans=new ArrayList<String>();
//遍历
for (String item : str) {
if (item.matches("\\d+")) {
ans.add(item);
}
//左括号 直接入栈
else if (item.equals("(")) {
oper.push(item);
}
//右括号 依次弹出栈顶元素 并加入ans 直到遇到(
else if(item.equals(")")){
while(!oper.peek().equals("(")){
ans.add(oper.pop());
}
oper.pop();//将左括号弹出
} else if (oper.empty() || oper.peek().equals("(")){
oper.push(item);
}else if(!oper.empty() && priority(item)>priority(oper.peek())){
oper.push(item);
} else{
while(!oper.empty() && priority(oper.peek())>=priority((item))){
ans.add(oper.pop());
}
oper.push(item);
}
}
//将oper中剩余的元素加入到ans中
while(!oper.empty()){
ans.add(oper.pop());
}
for (String an : ans) {
ret.add(an);
}
return ret;
}
public static int priority(String a){
if(a.equals("*") || a.equals("/")) return 1;
else if(a.equals("+") || a.equals("-")) return 0;
else return -1;
}
}