数据结构–后缀表达式(逆波兰计算器)(Java)
博客说明
文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除,谢谢!
介绍
使用后缀表达式做一个简单的计算器
思路
(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,由此得出最终结果
代码
package stack;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
/**
* @author guizimo
* @date 2020/4/6 12:25 下午
*/
public class PolandNotation {
public static void main(String[] args) {
String suffixExpression = "3 4 + 5 * 6 -";
//将字符串存入集合中,方便取出
List<String> listString = getListString(suffixExpression);
System.out.println(listString);
int res = calculate(listString);
System.out.printf("后缀表达式:%s = %d",suffixExpression,res);
}
//将逆波兰表达式的每个元素一次放入ArrayList中
public static List<String> getListString(String suffixExpression){
String[] split = suffixExpression.split(" ");
List<String> list = new ArrayList<String>();
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());
}
}
结果
感谢
尚硅谷
以及勤劳的自己