我正在尝试实现一种将两个多项式乘以列表并返回一个新列表作为结果的方法。 这是我到目前为止所拥有的:
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;
}
但是当我打印列表时,它没有显示任何内容。打印方法适用于我的加法、减法和一阶导数方法。这只是我的乘法方法不起作用。 这是我的打印方法:
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();
}
有什么想法吗?谢谢!
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
?
基本上你实际上并没有对结果做任何事情 只是玩你扔掉的临时变量。
我能够完成我的方法,所以就在这里!
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();
}
非常感谢对最佳实践的反馈!