You need to enable JavaScript to run this app. 实现多项式乘法时引用更新后poly节点触发NullPointerException的咨询
优惠活动
大模型
产品
解决方案
定价
更多

实现多项式乘法时引用更新后poly节点触发NullPointerException的咨询

多项式乘法方法NullPointerException根因与修复

核心触发原因

  • 当传入的poly1/poly2为空链表时,外层两重生成临时节点的while循环完全不会执行,poly会一直保持初始的null值,后续执行int i=poly.term.degree时,对空对象取term属性就会直接抛出空指针异常。
  • 代码中只在初始位置给combining赋值为poly头节点,进入内层遍历循环后,combining会顺着next指针一直走到链表尾部的null位置,但这个指针没有在每次外层循环开始新的degree匹配时重置回头节点位置;后续判断while (i >= combining.term.degree)时,combining已经是null,取combining.term.degree会再次触发空指针。
  • 现有逻辑的终止条件依赖会被遍历修改到null的combining节点做参照,和“使用循环中更新的poly头节点做遍历基准”的预期完全不匹配,从结构上就存在空指针风险。

具体修复步骤

  • 在方法开头加空输入前置校验:如果poly1或poly2任意一个为空,直接返回null,避免无效进入后续流程导致poly永远为初始空值。
  • 调整combining指针的作用域:将combining的声明移到外层degree遍历的循环内部,每一轮遍历匹配当前degree的所有项时,都将combining重新指回poly的头节点,避免指针走到链表尾部后丢失对有效节点的引用。
  • 替换外层循环的终止逻辑:直接将i的初始值设为poly头节点的degree值(因为临时poly链表是头插法构建的,头节点就是最高degree的有效节点),循环遍历从最高degree到0即可,完全不需要依赖会被修改到null的combining做终止参照,从逻辑上规避空指针。
  • 修正系数累加值的重置逻辑:每遍历完一个degree对应的所有节点后,将累加值csum重置为0,避免不同degree的系数累加值互相干扰,导致计算结果错误。

修正后的核心逻辑参考

public static Node multiply(Node poly1, Node poly2) {
    // 前置空值校验
    if (poly1 == null || poly2 == null) {
        return null;
    }
    Node poly3 = poly1;
    Node poly4 = poly2;
    Node poly = null;
    // 嵌套循环生成临时乘积节点链表的逻辑保持不变
    while (poly3 != null) {
        while (poly4 != null) {
            float x = poly3.term.coeff * poly4.term.coeff;
            int y = poly3.term.degree * poly4.term.degree;
            poly = new Node(x, y, poly);
            poly4 = poly4.next;
        }
        poly4 = poly2;
        poly3 = poly3.next;
    }
    // 临时链表为空的话直接返回
    if (poly == null) {
        return null;
    }
    Node finalpoly = null;
    int maxDegree = poly.term.degree;
    // 从最高degree往0遍历合并同类项
    for (int i = maxDegree; i >= 0; i--) {
        float csum = 0;
        // 每轮遍历前重置combining到临时链表头节点
        Node combining = poly;
        while (combining != null) {
            if (i == combining.term.degree) {
                csum += combining.term.coeff;
            }
            combining = combining.next;
        }
        if (csum != 0) {
            finalpoly = new Node(csum, i, finalpoly);
        }
    }
    return finalpoly;
}

内容的提问来源于stack exchange,提问作者hunter s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.24 04:15:06