我有一个方法,该方法将多项式Linked List
作为参数并返回一个新列表,该列表是多项式的导数。
这是我所拥有的:
private PolyNode derivative(PolyNode poly) {
PolyNode temp = new PolyNode(0, 0);
PolyNode res = temp;
// While both Lists are not empty
while (poly != null) {
if (poly.power > 0) {
temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
temp = temp.next;
poly = poly.next;
}
}
// Return new List, the result polynomial
return res.next;
}
当我运行程序时,它永远不会完成编译并部分返回列表;只有功率高于 0 的项。我尝试添加
if (poly.power == 0) {
temp.next = new PolyNode(0,0);
temp = temp.next;
poly = poly.next;
}
但这似乎行不通。有什么想法吗?
仔细观察你的while
循环:
// While both Lists are not empty
while (poly != null) {
if (poly.power > 0) {
temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
temp = temp.next;
poly = poly.next;
}
}
除非poly
power
大于零,否则不会更改。因此,当找到 0 power
的poly
时,您的循环就会卡住。
将其更改为:
while (poly != null) {
if (poly.power > 0) {
temp.next = new PolyNode(poly.coef * poly.power, poly.power - 1);
temp = temp.next;
}
poly = poly.next;
}
这样,您可以有效地抛出任何常量(power == 0
(,同时仍然循环poly
列表。