需要帮助编写一个将2个多项式相加在一起的方法(v2)



背景:我目前正在编写一种方法,将两个多项式(由两个文本文件给出(相加在一起。例如:

4.0x^5+-2.0x^3+2.0x+3.0

&

8.0x^4+4.0x^3+-3.0x+9.0

将导致:4.0x^5+8.0x^4+2.0x^3-1.0x+12

目前,我的输出只产生:8.0 x ^4+4.0 x ^5+2.0 x ^3-1.0 x+12——这是因为我的for循环的顺序,你可以在下面看到。我需要把条款整理好。

Polynomial answer = new Polynomial();

    //p = addZeroes(p);

    for (Node firstPoly = poly; firstPoly != null; firstPoly = firstPoly.next){
        boolean polyAdded = false;
        for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
            if (firstPoly.term.degree == secondPoly.term.degree){
            answer = addToRear(answer, (firstPoly.term.coeff + secondPoly.term.coeff), firstPoly.term.degree, null);
                    if (answer.poly.term.coeff == 0){
                        answer.poly = null;
                    }
                    polyAdded = true;

            }

        }
        if (polyAdded == false){
        answer = addToRear(answer, firstPoly.term.coeff, firstPoly.term.degree, null);
        if (answer.poly.term.coeff == 0){
            answer.poly = null;
        }
        }
    }
    for (Node secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next){
        boolean match = false;
        for (Node answerPoly = answer.poly; answerPoly != null; answerPoly = answerPoly.next){
            if (secondPoly.term.degree == answerPoly.term.degree){
                match = true;
                break;
            }

        }
        if (match == false){
        answer = addToRear(answer, secondPoly.term.coeff, secondPoly.term.degree, null);
        }
    }

    return answer;
    //alt + shift + r

}

谢谢。

您可以执行类似合并排序的方法,也可以执行哈希/成员身份查找。

合并排序应该看起来像

Node firstPoly = poly;
Node secondPoly = p.poly;
while (firstPoly != null && secondPoly != null) {
    if (firstPoly.term.degree == secondPoly.term.degree) {
        firstPoly.term.coeff += secondPoly.term.coeff;
        /* move both of them. */
        firstPoly = firstPoly.next;
        secondPoly = secondPoly.next;
    }   
    else if (firstPoly.term.degree > secondPoly.term.degree) {
        /* move the firstPoly */
        firstPoly = firstPoly.next;
    }   
    else /* if (firstPoly.term.degree < secondPoly.term.degree) */ {
        /* add secondPoly before firstPoly, and move the secondPoly */
        addBefore(firstPoly, secondPoly);
        secondPoly = secondPoly.next;
    }   
}   
/* flush secondPoly */
while (secondPoly != null) {
    addRear(secondPoly);
    secondPoly = secondPoly.next;
}   

若您喜欢基于查找的方法。

/* This returns a node with given degree. */
Node lookup(int degree);
/* Adds a new term. */
void addTerm(int degree, int coeff);
for (secondPoly = p.poly; secondPoly != null; secondPoly = secondPoly.next) {
    Node node = lookup(secondPoly.term.degree);
    if (node != null)
        node.coeff += secondPoly.term.coeff;
    else
        addTerm(secondPoly.term.degree, secondPoly.term.coeff);
}

相关内容

  • 没有找到相关文章

最新更新