逆波兰计算器分析与实现
只针对整型进行计算,重点关注思想
逆波兰表达式就是后缀表达式,中缀表达式转后缀表达式可见上一条贴
思路:首先输入一个逆波兰表达式如:(3+4)*5-6 ——>3 4 + 5 * 6 -
(1)从左至右扫描,将3和4压入栈
(2)遇到+运算符,因此弹出4和3(4为栈顶元素,3为次栈顶元素),计算出3+4的值,得7,再将7入栈
(3)将5入栈
(4)接下来是×运算符,因此弹出5和7,计算出7×5=35,将35入栈
(5)将6入栈
(6)最后是-运算符,计算出35-6的值,即29,由此得出结果
代码如下:
public class ReversePolndNotation {
public static void main(String[] args) {
String suffixExpression = "3 4 + 5 * 6 -";
List<String> listString = getListString(suffixExpression);
int calculate = calculate(listString);
System.out.println("计算的结果是:" + calculate);
}
//将一个逆波兰表达式,依次将数据和运算符放到ArrayList中
public static List<String> getListString(String suffixException){
String[] split = suffixException.split(" ");
List<String> list = new ArrayList<>();
for (String ele : split){
list.add(ele);
}
return list;
}
public static int calculate(List<String> ls){
Stack<String> stack = new Stack<>();
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;
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());
}
}

本篇文章是根据尚硅谷数据结构视频进行总结和代码实现,谢谢尚硅谷大学教会我java知识
本文介绍了逆波兰表达式的计算原理及其实现过程,通过Java代码展示了如何处理后缀表达式进行整数计算。主要步骤包括扫描表达式,将数字入栈,遇到运算符时进行相应的计算并更新栈。最终,通过栈内剩余的数值得到计算结果。
&spm=1001.2101.3001.5002&articleId=122102421&d=1&t=3&u=04eeab4156b74529ad5f625446d12f0d)
1703

被折叠的 条评论
为什么被折叠?



