当前位置: 首页 > news >正文

栈的简单应用(利用Stack进行四则混合运算)(JAVA)

目录

中缀表达式转后缀表达式

图解

代码实现过程:

完整代码: 

利用后缀表达式求值:

完整代码:


 

首先我们得先了解逆波兰表达式

中缀表达式转后缀表达式

所谓的中缀表达式其实就是我们平时写的例如:3+4\times (2+ 2)+2\div 2;而它的后缀表达式(也成为逆波兰表达式) 3\; 4\; 2\; 2+ \times + 2\; 2 \;\div +

后缀表达式:指的是不包含括号运算符放在两个运算对象的后面,所有的计算按运算符出现的顺序,严格从左向右进行不再考虑运算符的优先规则)。

我们如果要利用程序来进行四则混合运算最重要的就是将输入的中缀表达式转后缀表达式

首先我们假设运算符中只有 加 减 乘 除 和 括号不然的话程序太复杂了(其实是我不会写【哭】)。

图解

代码实现过程:

首先我们先写一个方法 返回值是动态字符串数组(为了后面好计算),形参为字符串类型(因为输入值不只有数字还有运算符)。这里会用到栈所以也定义一个栈。

    public ArrayList<String> midChangeEng(String str) {//这里用动态数组就不用担心不够用ArrayList<String> ret = new ArrayList<String>();Stack<Character> stack = new Stack<>();}

此时再创建一个新方法用来判断传入字符是不是运算符 

    public boolean isOperator(char s) {if (s == '+' || s == '-' || s == '*' || s == '/' || s == '(' || s == ')') {return true;}return false;}

我们再利用运算符再ASCII码中的位置,创建一个数组用来表示它们的优先级

int[] able = {1,0,0,0,0,1};//分别代表 * + (null) - (null) / 的优先级 

 利用循环遍历字符串

        //遍历字符串for (int i = 0; i < str.length(); i++) {char a = str.charAt(i);String tmp = "";//用来暂时存储出栈的数字if (isOperator(a)) {//是操作数}else{//如果是数字就放到ret中}}return ret;

对操作数的操作 ,可是此段代码中重复代码过多,所以可以将其封装成一个方法。

            if (isOperator(a)) {//是操作数switch (a) {case '+'://判断如果优先级不大于栈顶的元素那么就先出栈在入栈if(!stack.isEmpty()) {//出栈while(!stack.isEmpty() && stack.peek() != '(' && able[(int)stack.peek() - 42] >= able[(int)a-42]) {String b = "";b += stack.pop();ret.add(b);}}stack.push(a);break;case '-':if(!stack.isEmpty()) {//出栈while(!stack.isEmpty() && stack.peek() != '(' && able[(int)stack.peek() - 42] >= able[(int)a-42]) {String b = "";b += stack.pop();ret.add(b);}}stack.push(a);break;case '*':if(!stack.isEmpty()) {//出栈while(!stack.isEmpty() && stack.peek() != '(' && able[(int)stack.peek() - 42] >= able[(int)a-42]) {String b = "";b += stack.pop();ret.add(b);}}stack.push(a);break;case '/':if(!stack.isEmpty()) {//出栈while(!stack.isEmpty() && stack.peek() != '(' && able[(int)stack.peek() - 42] >= able[(int)a-42]) {String b = "";b += stack.pop();ret.add(b);}}stack.push(a);break;case '(':stack.push(a);break;case ')':while(!stack.isEmpty() && stack.peek() != '(') {String b = "";b += stack.pop();ret.add(b);}stack.pop();//删除‘(’break;}}

 如果是数字就进行以下操作

            else{//如果是数字就放到ret中String tmp = "";while(i < str.length() && !isOperator(str.charAt(i))) {//数字有可能是多位的tmp += str.charAt(i);i++;}i--;ret.add(tmp);}

再出函数之前要先将栈里面的全部导出来

        //将栈里面剩余的全部出栈while(!stack.isEmpty()) {String b = "";b += stack.pop();ret.add(b);}return ret;

完整代码: 

    public static ArrayList<String> midChangeEng(String str) {//这里用动态数组就不用担心不够用ArrayList<String> ret = new ArrayList<String>();Stack<Character> stack = new Stack<>();int[] able = {1,0,0,0,0,1};//分别代表 * + (null) - (null) / 的优先级//遍历字符串for (int i = 0; i < str.length(); i++) {char a = str.charAt(i);if (isOperator(a)) {//是操作数switch (a) {case '+'://判断如果优先级不大于栈顶的元素那么就先出栈在入栈abcd(ret, stack, able, a);break;case '-':abcd(ret, stack, able, a);break;case '*':abcd(ret, stack, able, a);break;case '/':abcd(ret, stack, able, a);break;case '(':stack.push(a);break;case ')':while(!stack.isEmpty() && stack.peek() != '(') {String b = "";b += stack.pop();ret.add(b);}stack.pop();//删除‘(’break;}}else{//如果是数字就放到ret中String tmp = "";while(i < str.length() && !isOperator(str.charAt(i))) {//数字有可能是多位的tmp += str.charAt(i);i++;}i--;ret.add(tmp);}}//将栈里面剩余的全部出栈while(!stack.isEmpty()) {String b = "";b += stack.pop();ret.add(b);}return ret;}

利用后缀表达式求值:

这部分比较简单所以就直接展示了

完整代码:

        public int evalRPN(String[] tokens) {Stack<Integer> stack = new Stack<>();for (int i = 0; i < tokens.length; i++) {if (isOperator(tokens[i])) {int num2 = stack.pop();int num1 = stack.pop();switch(tokens[i].charAt(0)) {case '+':stack.push(num1 + num2);break;case '-':stack.push(num1 - num2);break;case '*':stack.push(num1 * num2);break;case '/':stack.push(num1 / num2);break;}}else {stack.push(Integer.parseInt(tokens[i]));}}return stack.pop();}public boolean isOperator(String str) {if (str.length() != 1) {return false;}if (str.charAt(0) == '+' || str.charAt(0) == '-' || str.charAt(0) == '*' || str.charAt(0) == '/') {return true;}return false;}

http://www.lryc.cn/news/173394.html

相关文章:

  • Python---异常
  • 视频编解码器H.264和H265有什么区别?
  • 网络安全进阶学习第十六课——业务逻辑漏洞介绍
  • 华为OD:跳房子I
  • C语言自定义类型详解(1)结构体知识汇总
  • 小程序中如何查看会员的访问记录
  • SpringCloud Alibaba - Sentinel
  • 内存泄漏,内存溢出,抽象类和接口,netstat、ping、ifconfig的区别
  • TensorFlow安装 ,在原本的虚拟环境下配置Tensorflow.
  • 如何使用HTML, CSS和JavaScript开发一个浏览器打字游戏:从零到一的详细步骤与完整代码教程
  • 安卓玩机搞机----不用刷第三方官改固件即可享受“高级设置”的操作 ChiMi安装使用步骤
  • 代码随想录|392.判断子序列,115.不同的子序列(需要二刷)
  • Linux——文件系统
  • 《动手学深度学习 Pytorch版》 7.3 网络中的网络(NiN)
  • 古代有没有电子元器件?
  • log4j2或者logback配置模版实现灵活输出服务名
  • 使用HTTP爬虫ip中的常见误区与解决方法
  • MySQL学习笔记3
  • 快速掌握ES6
  • 电池厂提供excel电池曲线zcv到mtk电池曲线zcv转换
  • 重写和重载、抽象类和接口
  • Untiy UDP局域网 异步发送图片
  • 移动端H5封装一个 ScrollList 横向滚动列表组件,实现向左滑动
  • Docker一键安装和基本配置
  • MVC设计思想理解和ASP.NET MVC理解
  • 大模型应用选择对比
  • c++STL概述
  • 利用容器技术优化DevOps流程
  • 91 # 实现 express 的优化处理
  • arcgis拓扑检查实现多个矢量数据之间消除重叠区域