我已經寫了一個代表使用鏈表的多項式的類(該列表中的成員是我稱爲PolyNodes的另一個類的對象)。 那堂課我寫這個方法:鏈接列表方法無法正常工作(java)
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;
}
我不明白爲什麼,但我得到錯誤的結果。我經歷了幾十次代碼,仍然找不到任何可能導致問題的事情。 問題產生如下: 當我打印列表1,我得到:
-5.0x^20+5.0x^17+4.0x^11+6.0x^8-5.0x^7+16.0x+1.0
當我打印列表2,我得到
-3.0x^100+2.0x^17-3.0x^4+4.0x
然而,當我打印list1.addPol(列表2)
-3.0x^100-10.0x^20+10.0x^17+8.0x^11+12.0x^8-10.0x^7+32.0x+2.0
如果任何人都可以請告訴我是什麼導致這種情況,我會非常appriciate它。提前致謝。
這需要所謂的「調試」 - 您需要確定您的代碼在做什麼,可能是在逐個語句級別上。有些程序可以幫助實現這個功能,稱爲調試程序,您可以在IDE(例如eclipse和IntelliJ)中找到它們,甚至還有一個原始程序包(或者至少曾經被包含在Java開發環境中)。如果您沒有這些和/或不想使用它們,您可以在代碼中添加「trace」語句以確定不同點處的不同變量的值。我們通常不會在這裏爲人們調試代碼。 – arcy