我编写了一个使用链表表示多项式的类(该列表中的成员是我创建的另一个类 PolyNodes 的对象)。 在该类中我编写了这个方法:
public Polynom addNode (PolyNode p)
{
if (p==null) //if the polynode to be added is null, the same polynom is returned
return this;
if (_head==null) //If the head is null, the polynom is empty and the polynode becomes the polynom
{
_head=p;
return this;
}
PolyNode curr = _head, prev = null;
while(curr != null) //when curr becomes null that means we reached the end of the polynom hence we reached the end of the loop as well
{
if (p.getPower() > curr.getPower()) //Upon reaching the first term whose power is lower than p's power
{
p.setNext(curr);
if (prev == null) //When curr is the polynom's head
_head = p;
else
prev.setNext(p);
return this;
}
else if (p.getPower() == curr.getPower()) //If the polynom already has a term with the same power, p's and curr's coefficients are summed up
{
curr.setCoefficient(curr.getCoefficient() + p.getCoefficient());
return this;
}
prev = curr;
curr = curr.getNext();
}
//If the method reached outside of the loop then there is no term in the polynom whose power is smaller than p's, and p will become the last term in the polynom
p.setNext(null);
prev.setNext(p);
return this;
}
当我尝试编写 addPol() 方法时,问题就开始了。
public Polynom addPol (Polynom other)
{
for (PolyNode temp=other._head ; temp!=null ; temp=temp.getNext())
{
addNode(temp);
}
return this;
}
我不明白为什么,但我得到了错误的结果。我检查了代码几十次,仍然找不到任何可能导致问题的地方。 问题如下: 当我打印 list1 时,我得到:
-5.0x^20+5.0x^17+4.0x^11+6.0x^8-5.0x^7+16.0x+1.0
当我打印 list2 时,我得到
-3.0x^100+2.0x^17-3.0x^4+4.0x
但是,当我打印 list1.addPol(list2) 时
-3.0x^100-10.0x^20+10.0x^17+8.0x^11+12.0x^8-10.0x^7+32.0x+2.0
如果有人能告诉我是什么原因造成的,我将非常感激。提前致谢。
最佳答案
当您将节点添加到新列表时,其属性会发生更改,因此当您移动到下一个时,您也会移动到第二个列表中的下一个。
您最好只使用提供的 LinkedList 类,而不是尝试自己重新发明它。
关于java - 链接列表方法无法正常工作(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21416251/