[英]Adding Polynomials Using Linked Lists Java
我正在嘗試添加兩個多項式,但是無論何時執行我的代碼,它都會返回零。 我希望有人可以向我指出我在做什么以及如何解決。 謝謝
public static Node add(Node poly1, Node poly2) {
float coeff = 0;
int degree = 0;
Node polyAdd = new Node (coeff,degree,null);
while (poly1 != null && poly2 != null ) {
if (poly1.term.degree == poly2.term.degree) {
degree = poly1.term.degree;
coeff = poly1.term.coeff + poly2.term.coeff;
poly1 = poly1.next;
poly2 = poly2.next;
} else if (poly1.term.degree > poly2.term.degree) {
degree = poly1.term.degree;
coeff = poly1.term.coeff;
poly1 = poly1.next;
} else {
degree = poly2.term.degree;
coeff = poly2.term.degree;
poly2 = poly2.next;
}
polyAdd = new Node (coeff, degree, null);
polyAdd = polyAdd.next;
}
return polyAdd;
}
您試圖將鏈接列表poly1和poly2加在一起,結果將存儲在新的鏈接列表中。
但是,您沒有正確構建結果鏈接列表。 在為每個不同的度數創建一個新節點時,您沒有正確創建新節點並將它們鏈接在一起。 編碼:
polyAdd = new Node (coeff, degree, null);
刪除對先前polyAdd的任何引用。
使鏈表保持完整的正確方法是:
polyAdd.next = new Node(coeff, degree, null);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.