用栈实现逆波兰计算器思路
1)输入一个逆波兰表达式(后缀表达式),使用栈,计算其结果
思路分析
比如(3+4)5-6 ,对应的后缀表达式为 3 4 + 5 * 6 -,针对后缀表达式求值步骤为:
(1) 从左至右扫描,将3和4 压入堆栈
(2) 遇到符号(+,-,,/),则弹出数字,并且进行运算,
(3) 计算完成,再压入栈,为res,最终结果就是res,进行弹出栈
代码实现
package database;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class PolandNotation {
public static void main(String[] args) {
//定义一个逆波兰表达式 (3+4)*5-6
String nblexpresion ="3 4 + 5 * 6 -";
List<String> nlist=getlistString(nblexpresion);
System.out.println(nlist);
int res =charters(nlist);
System.out.println(res);
}
public static List<String> getlistString(String nblexpresion){
//将表达式分割
String split[] = nblexpresion.split(" ");
//保存进入一个集合
List<String> list =new ArrayList<>();
for (String ele: split
) {
list.add(ele);
}
return list;
}
//传递方法 遍历 入栈 运算 出栈 再入栈
public static int charters (List<String> lis){
Stack<String> stack =new Stack<String>();
for (String s:lis
) {
if (s.matches("\\d+")){
stack.push(s);
}else {
//pop出两个数,且进行计算,再入栈
int num2= Integer.parseInt(stack.pop());
int num1 =Integer.parseInt(stack.pop());
int res=0;
if (s.equals("+")){
res=num1+num2;
}else if (s.equals("-")){
res=num2-num1;
}else if (s.equals("*")){
res=num1*num2;
}else if (s.equals("/")){
res=num2/num1;
}else {
throw new RuntimeException("运算符有误");
}
//入栈的res就是结果
stack.push(res+"");
}
}
return Integer.parseInt(stack.pop());
}
}