【发布时间】:2014-01-29 18:11:46
【问题描述】:
我编写了一个类,它使用链表表示多项式(该列表中的成员是我创建的另一个名为 PolyNodes 的类的对象)。在那个类中,我编写了这个方法(这个方法应该得到一个参数多项式并将其添加到现有的多项式中,返回两个多项式的总和同时不更改参数):
public Polynom addPol(Polynom other)
{
if (_head==null) //If the head is null, this polynom is empty and
the other polynom becomes this polynom
{
_head=other._head;
return this;
}
if(other._head==null) //if the polynom to be added is null, the
same polynom is returned
return this;
PolyNode curr=_head, curr2=other._head, prev=null, prev2=null;
while(curr!=null && curr2!=null)
{
if(curr2.getPower()>curr.getPower())
{
System.out.println("1 " + curr2.getCoefficient());
PolyNode copy = new PolyNode(curr2.getPower() ,curr2.getCoefficient() );
System.out.println("2 " + curr2.getCoefficient());
copy.setNext(curr);
if (prev==null)
_head=copy;
else
prev.setNext(copy);
}
else if (curr2.getPower() == curr.getPower()) //If this polynom already
has a term with the same power, curr2's and curr's coefficients are summed up
{
curr.setCoefficient(curr.getCoefficient() + curr2.getCoefficient());
}
//Moving the pointer to the next node in the polynom
if(curr2.getPower()>curr.getPower())
{
prev2=curr2;
curr2=curr2.getNext();
}
else if(curr.getPower()>curr2.getPower())
{
prev=curr;
curr=curr.getNext();
}
else if(curr.getPower()==curr2.getPower())
{
prev2=curr2;
curr2=curr2.getNext();
prev=curr;
curr=curr.getNext();
}
}
if(curr2!=null) //If there are nodes left in other
{
for(;prev!=null;curr2=curr2.getNext()) //add them to this
{
PolyNode copy = new PolyNode(curr2.getPower() ,curr2.getCoefficient() );
prev.setNext(copy);
prev=curr2;
}
}
return this;
}
由于某种原因(这超出了我的范围),当我尝试保持它不变时,当我使用此方法时,参数多项式也发生了变化。我不知道为什么。有人可以帮帮我吗?我在这里失去了希望。
【问题讨论】:
-
我没有深入阅读代码,但是您正在更改 curr2,它最初是参数的头部。您的问题可能与此有关。
-
能否请您参考我正在更改 curr2 的行?
-
我不知道确切的行,但你有“curr2=curr2.getNext();”在 2 个不同的地方。用 ctrl+f 检查 curr2 你会看到的。
标签: java linked-list polynomial-math