【问题标题】:Adding Polynomials Using Linked Lists Java使用链表 Java 添加多项式
【发布时间】:2018-02-07 00:59:31
【问题描述】:

我正在尝试添加两个多项式,但是每当执行我的代码时,它都会返回零。我希望有人可以向我指出我在做什么以及如何解决它。谢谢

    public static Node add(Node poly1, Node poly2) {

    float coeff = 0;
    int degree = 0;
    Node polyAdd = new Node (coeff,degree,null);
    while (poly1 != null && poly2 != null ) {
        if (poly1.term.degree == poly2.term.degree) {
            degree = poly1.term.degree;
            coeff = poly1.term.coeff + poly2.term.coeff;
            poly1 = poly1.next;
            poly2 = poly2.next;
        } else if (poly1.term.degree > poly2.term.degree) {
            degree = poly1.term.degree;
            coeff = poly1.term.coeff;
            poly1 = poly1.next;
        } else {
            degree = poly2.term.degree;
            coeff = poly2.term.degree;
            poly2 = poly2.next;
        }
        polyAdd = new Node (coeff, degree, null);
        polyAdd = polyAdd.next;
    }
    return polyAdd;
}

【问题讨论】:

  • 这段代码只返回一个地方,它返回一个Node - 它怎么能返回zero
  • 你试过调试这段代码吗?
  • 请更新您的问题以在minimal, complete, and verifiable example 中显示您已经尝试过的内容。如需更多信息,请参阅how to ask good questions,并拨打tour of the site :)
  • 我认为它返回的节点 (0,0,null) 是 0^0
  • 好吧,poly1poly2 可能为空,但只有你自己知道

标签: java singly-linked-list polynomial-math


【解决方案1】:

您正在尝试将链表 poly1 和 poly2 相加,结果将存储在一个新的链表中。

但是,您没有正确构建生成的链表。当您为每个不同的学位创建一个新节点时,您没有正确地创建新节点并将它们链接在一起。 代码:

polyAdd = new Node (coeff, degree, null);

删除对先前 polyAdd 的任何引用。

保持链表完整的正确方法是:

polyAdd.next = new Node(coeff, degree, null);

【讨论】:

    猜你喜欢
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-19
    相关资源
    最近更新 更多