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

后缀表达式中缀表达式转后缀表达式

后缀表达式的计算机求值

计算规则

从左至右扫描表达式,遇到数字时,将数字压入堆栈,遇到运算符时,弹出栈顶的两个数,用运算符对它们做相应的计算(次顶元素 和 栈顶元素),并将结果入栈;重复上述过程直到表达式最右端,最后运算得出的值即为表达式的结果。

举例分析

例如: (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,由此得出最终结果
扫描元素s1(栈底->栈顶)说明
33数字,入栈
43 4数字,入栈
+7运算符,弹出栈顶的两个数,用运算符对它们做相应的计算(顺序:次顶元素 和 栈顶元素),并将结果入栈
57 5数字,入栈
*35运算符,弹出栈顶的两个数,用运算符对它们做相应的计算(顺序:次顶元素 和 栈顶元素),并将结果入栈
635 6数字,入栈
-29运算符,弹出栈顶的两个数,用运算符对它们做相应的计算(顺序:次顶元素 和 栈顶元素),并将结果入栈
29最终结果保存在操作数栈中

代码实现

import java.util.Stack;/*** @Author: * @Create: 2024-10-01 10:36* @Description:*  (3+4)×5-6  --> 3 4 + 5 × 6 -*/
public class 后缀表达式 {public static void main(String[] args) {String expression = "3 4 + 5 * 6 - ";String[] str = expression.split(" ");Stack<Integer> numStack = new Stack<>();int res = 0;for (String s : str) {if (s.matches("\\d+")) {numStack.push(Integer.parseInt(s));} else {Integer num1 = numStack.pop();Integer num2 = numStack.pop();switch (s) {case "+":res = num2 + num1;break;case "-":res = num2 - num1;break;case "*":res = num2 * num1;break;case "/":res = num2 / num1;break;default:throw new ArithmeticException("运算符有误");}numStack.push(res);}}System.out.println(res);}
}

逆波兰计算器

逆波兰表达式(后缀表达式)支持小括号和多位数整数计算,后缀表达式适合计算机进行运算,但是人却不太容易写出来,尤其是表达式很长的情况下,因此在开发中,我们需要将中缀表达式转成后缀表达式。

中缀表达式转后缀表达式规则

具体步骤如下:

  1. 初始化两个栈:存储中间结果的栈s1和运算符栈s2;定义-+优先级为1,*/优先级为2,其他0
  2. 从左至右扫描中缀表达式;
  3. 遇到操作数时,将其压s1;
  4. 遇到运算符时,比较其与s2栈顶运算符的优先级:
    1. 如果s2不为空 && 优先级<=栈顶运算符(优先级的定义判定了栈顶运算符为左括号“(”的情况,所以不用在考虑遇到做括号的情况),将s2栈顶的运算符弹出并压入到s1中,循环判断,再次转到(4-1)与s2中新的栈顶运算符相比较;
    2. 出了循环,将运算符压入s2;
  5. 遇到括号时:
    1. 如果是左括号“(”,则直接压入s2
    2. 如果是右括号“)”,则依次弹出s2栈顶的运算符,并压入s1,直到遇到左括号为止,此时将这一对括号丢弃
  6. 重复步骤3至5,直到表达式的最右边
  7. 将s2中剩余的运算符依次弹出并压入s1
  8. 依次弹出s1中的元素并输出,结果的逆序即为中缀表达式对应的后缀表达式

举例分析

将中缀表达式 “1+((2+3)*4)-5” 转换为后缀表达式 "1 2 3 + 4 * + 5 –" 的过程如下:

扫描元素s1(栈底->栈顶)s2(栈底->栈顶)说明
1操作数,直接入栈s1
+1+s2为空,入栈s2
(1+ (左括号,直接入栈s2
(1+ ( ( 左括号,直接入栈s2
21 2+ ( ( 操作数,直接入栈s1
+1 2+ ( ( +s2栈顶运算符为左括号,入栈s2
31 2 3 + ( ( +操作数,直接入栈s1
)1 2 3 ++ ( 右括号,依次弹出s2栈顶的运算符,压入s1,直到遇到左括号为止,此时将这一对括号丢弃
*1 2 3 ++ ( *s2栈顶运算符为左括号,入栈s2
41 2 3 + 4+ ( *操作数,直接入栈s1
)1 2 3 + 4 *+右括号,依次弹出s2栈顶的运算符,压入s1,直到遇到左括号为止,此时将这一对括号丢弃
-1 2 3 + 4 * +--优先级不比+高,将+弹出并压入到s1中,此时s2为空,-入栈s2
51 2 3 + 4 * + 5-操作数,直接入栈s1
1 2 3 + 4 * + 5 -s2中剩余的运算符依次弹出并压入s1,结果为s1出栈的逆序

代码实现

import java.util.ArrayList;
import java.util.Stack;/*** @Author: * @Create: 2024-10-01 11:58* @Description: 1+((2+3)*4)-5 --> 1 2 3 + 4 * + 5 –*/
public class 中缀转后缀 {public static void main(String[] args) {String infix = "1+((2+3)*4)-5";ArrayList<String> suffixList = new ArrayList<>();Stack<String> oper = new Stack<>();int len = infix.length();for (int i = 0; i < len; i++) {char c = infix.charAt(i);if (Character.isDigit(c)) {int j = i;while (j < len && Character.isDigit(infix.charAt(j))) {j++;}suffixList.add(infix.substring(i, j));i = j - 1;} else if (c == '(') {oper.push(c + "");} else if (c == ')') {while (!oper.isEmpty() && !oper.peek().equals("(")) {suffixList.add(oper.pop());}oper.pop(); // 弹出左括号} else { // 运算符while (!oper.isEmpty() && getPriority(c + "") <= getPriority(oper.peek())) {suffixList.add(oper.pop());}oper.push(c + "");}}// 弹出剩下运算符while (!oper.isEmpty()) {suffixList.add(oper.pop());}System.out.println(suffixList);}private static int getPriority(String operator) {if ("*".equals(operator) || "/".equals(operator)) return 2;else if ("+".equals(operator) || "-".equals(operator)) return 1;else return 0;}
}

逆波兰计算器代码实现

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;/*** @Author: * @Create: 2024-10-01 13:51* @Description:*/
public class 逆波兰计算器 {public static void main(String[] args) {Scanner in = new Scanner(System.in);String infix = in.nextLine().replace(" ", "");// 转化后缀表达式List<String> suffix = changeToSuffix(infix);// 计算后缀表达式int res = calculateSuffix(suffix);System.out.println(res);}private static int calculateSuffix(List<String> suffix) {Stack<Integer> nums = new Stack<>();int res = 0;for (String s : suffix) {if (s.matches("\\d+")) {nums.push(Integer.parseInt(s));} else {Integer num1 = nums.pop();Integer num2 = nums.pop();switch (s) {case "*":res = num2 * num1;break;case "/":res = num2 / num1;break;case "+":res = num2 + num1;break;case "-":res = num2 - num1;break;default:throw new ArithmeticException("运算符有误");}nums.push(res);}}return res;}private static List<String> changeToSuffix(String infix) {Stack<String> oper = new Stack<>();ArrayList<String> res = new ArrayList<>();int len = infix.length();for (int i = 0; i < len; i++) {char c = infix.charAt(i);if (Character.isDigit(c)) {int j = i;while (j < len && Character.isDigit(infix.charAt(j))) {j++;}res.add(infix.substring(i, j));i = --j;} else if (c == '(') {oper.push(c + "");} else if (c == ')') {while (!oper.isEmpty() && !"(".equals(oper.peek())) {res.add(oper.pop());}oper.pop();} else {while (!oper.isEmpty() && getPriority(c + "") <= getPriority(oper.peek())) {res.add(oper.pop());}oper.push(c + "");}}while (!oper.isEmpty()) {res.add(oper.pop());}return res;}private static int getPriority(String operator) {if ("*".equals(operator) || "/".equals(operator)) return 2;else if ("+".equals(operator) || "-".equals(operator)) return 1;else return 0;}
}

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

相关文章:

  • Qemu开发ARM篇-7、uboot以及系统网络连接及配置
  • 两数相加leetcode
  • C0004.Qt中QComboBox设置下拉列表样式后,下拉列表样式无效的解决办法
  • AI 对话工具汇总
  • 面试题05.08绘制直线问题详解(考察点为位运算符)
  • 埃及 Explained
  • 【Linux】第一个小程序——进度条实现
  • 如何确定光纤用几芯 用光纤与网线区别在哪里
  • 使用Chrome浏览器时打开网页如何禁用缓存
  • zabbix7.0创建自定义模板的案例详解(以监控httpd服务为例)
  • 从零开始Ubuntu24.04上Docker构建自动化部署(五)Docker安装jenkins
  • 【JS】访问器成员
  • 五子棋双人对战项目(3)——匹配模块
  • 开源软件简介
  • Bruno:拥有 11.2k star 的免费开源 API 测试工具
  • C动态内存管理
  • 系列二、案例实操
  • Python编码系列—Python状态模式:轻松管理对象状态的变化
  • 卸载WSL(Ubuntu),卸载linux
  • Lumerical脚本语言-系统(System)
  • QT 界面编程中使用协程
  • macOS 开发环境配置与应用开发
  • 第13讲 实践:设计SLAM系统
  • NeRF2: Neural Radio-Frequency Radiance Fields 笔记
  • 以太网交换安全:MAC地址表安全
  • CSS综合页布面局案例
  • 低代码可视化-UniApp二维码可视化-代码生成器
  • Electron 使用 Nodemon 配置自动重启
  • JVM和GC监控技术
  • Android中级控件