【发布时间】:2015-09-29 16:44:13
【问题描述】:
背景: 我目前正在编写一种将两个多项式(由 2 个文本文件给出)相加的方法。比如:
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.0x^5 + 2.0x^3 - 1.0x + 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
}
谢谢。
【问题讨论】:
标签: java data-structures linked-list