package com.stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Poland {
public static void main(String[] args) {
String suff= "30 4 + 5 * 6 -";
List<String> list=getListString(suff);
System.out.println(list);
System.out.println(calculate(list));
}
public static List<String> getListString(String suff){
String[] split = suff.split(" ");
List<String> list=new ArrayList<String>();
for(String s:split){
list.add(s);
}
return list;
}
public static int calculate(List<String> list){
Stack<String> stack = new Stack<String>();
for(String item:list){
if(item.matches("\\d+")){
stack.add(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());
}
}
标签:String,res,list,item,波兰,计算器,数据结构,stack,num1 From: https://www.cnblogs.com/xming2023/p/17092622.html