英文:
Linkedlist polynomial why my output only print first term
问题
我刚刚编写了一个程序,用于添加两个多项式链接列表。我的输出只打印出多项式的第一个项。
我无法弄清楚有什么错误。我想在这里得到一些帮助。有人可以告诉我代码有什么问题吗?
public void addNode(int cof, int exp) {
PNode node = new PNode(cof, exp);
if (first == null) {
first = last = node;
return;
}
last.next = node;
last = node;
}
public PolynomialLinkedList add(PolynomialLinkedList s) {
PolynomialLinkedList sum = new PolynomialLinkedList();
// 实现这个方法
PNode list1 = first;
PNode list2 = s.first;
while (list1 != null && list2 != null) {
if (list1.exp == list2.exp) {
sum.addNode(list1.coe + list2.coe, list1.exp);
list1 = list1.next;
list2 = list2.next;
} else if (list1.exp > list2.exp) {
sum.addNode(list1.coe, list1.exp);
list1 = list1.next;
} else if (list2.exp > list1.exp) {
sum.addNode(list2.coe, list2.exp);
list2 = list2.next;
}
}
return sum;
}
(注意:此处只提供翻译后的代码,不包含额外内容。)
英文:
I just wrote a program that add two polynomial linked-list. my output only prints first term of the polynomials.
I cannot figure out what bug is. I want to get some help here. could someone tell what's wrong with my code.
public void addNode(int cof, int exp) {
PNode node = new PNode(cof, exp);
if (first == null) {
first = last = node;
return;
}
last.next = node;
last = node;
}
public PolynomialLinkedList add(PolynomialLinkedList s) {
PolynomialLinkedList sum = new PolynomialLinkedList();
//implement this method
PNode list1 = first;
PNode list2 = s.first;
while (list1 != null && list2 != null) {
if (list1.exp == list2.exp) {
sum.addNode(list1.coe + list2.coe, list1.exp);
list1 = list1.next;
list2 = list2.next;
} else if (list1.exp > list2.exp) {
sum.addNode(list1.coe, list1.exp);
list1 = list1.next;
} else if (list2.exp > list1.exp) {
sum.addNode(list2.coe, list2.exp);
list2 = list2.next;
}
}
return sum;
}
答案1
得分: 2
如果其中一个列表先结束,其他列表中的剩余项目将被忽略,不会被添加到总和中。
添加额外的循环
while(list1 != null) {
sum.addNode(list1.coe, list1.exp);
list1 = list1.next;
}
和
while(list2 != null) {
sum.addNode(list2.coe, list2.exp);
list2 = list2.next;
}
英文:
If one of the lists finishes first, the rest of the items in other list are ignored and are not getting added to the sum.
Add additional loops
while(list1 != null) {
sum.addNode(list1.coe,list1.exp);
list1=list1.next;
}
and
while(list2 != null) {
sum.addNode(list2.coe,list2.exp);
list2=list2.next;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论