使用链接列表乘以多项式

时间:2018-04-16 02:27:02

标签: java linked-list

我正在尝试实现一个方法,将两个多项式相乘作为列表,并返回一个新列表作为结果。 这是我到目前为止所做的:

private PolyNode multiply(PolyNode first, PolyNode second) {
    PolyNode temp = new PolyNode(0, 0);
    PolyNode res = temp;

    while(first!=null) {
        while(second!=null) {
            //Multiply first term with all the terms with all terms in the second.
            temp = new PolyNode(first.coef * second.coef, first.power + second.power);
            temp = temp.next;
            second = second.next;
        }
        //Move to next term
        first = first.next;
    }
    return res.next;
}

但是当我打印列表时,它没有显示任何内容。打印方法适用于我的加法,减法和一阶导数方法。这只是我的Multiply方法无法正常工作。 这是我的打印方法:

void printPoly(PolyNode curr) {

    if(curr == null) {
        return;
    }

    while (curr != null) {
        if(curr.power == 0) {
            System.out.print(curr.coef + "");
            curr = curr.next;
        }
        else if(curr.power == 1){
            System.out.print(curr.coef + "x ");
            curr = curr.next;
        }
        else {
            System.out.print(curr.coef + "x^" + curr.power + " + ");
            curr = curr.next;
        }
    }
    System.out.println();
}

有什么想法?谢谢!

2 个答案:

答案 0 :(得分:0)

PolyNode temp = new PolyNode(0, 0);
PolyNode res = temp;

然后

temp = new PolyNode(first.coef * second.coef, first.power + second.power);

所以res指向某个对象。 temp现在指向与res无关的一些新对象。

然后

return res.next;

我认为这是null

基本上你实际上并没有对结果做任何事情  只是玩你扔掉的临时变量。

答案 1 :(得分:0)

我能够完成我的方法,所以在这里!

private PolyNode multiply(PolyNode first, PolyNode second) {
    PolyNode temp = new PolyNode(0, 0);
    PolyNode res = temp;

    while(first!=null) {
        while(second!=null) {
            //Multiply first term with all the terms with all terms in the second.
            temp.next = new PolyNode(first.coef * second.coef, first.power + second.power);
            temp = temp.next;
            second = second.next;
        }
        //Move to next term.
        first = first.next;
    }
    return res.next;
}

这是我的打印列表方法:

void printPoly(PolyNode curr) {

    if(curr == null) {
        return;
    }

    while (curr != null) {
        if(curr.power == 0) {
            System.out.print(curr.coef + "");
            curr = curr.next;
        }
        else if(curr.power == 1){
            System.out.print(curr.coef + "x ");
            curr = curr.next;
        }
        else {
            System.out.print(curr.coef + "x^" + curr.power + " ");
            curr = curr.next;
        }
    }
    System.out.println();
}

非常感谢对最佳做法的反馈!