我想爲鏈表創建一個添加方法,但出於某種原因(對我來說這並不明顯,實際上我來這裏是爲了幫助查找錯誤)每次都會進入無限循環。爲什麼會無限循環? (Java)
編輯:我發現了錯誤,我會繼續我的原代碼的註釋與該修正的代碼
public void insert(String majorName)
{
MajorNode newNode = new MajorNode(majorName, 1);
boolean inList = false;
MajorNode current = first;
if(isEmpty())
{
first = newNode;
// inList = true;
}
else
{
while(current.next != null)
{
if(current.majorName.equalsIgnoreCase(majorName))
{
current.frequency++;
inList = true;
break;
}
else
{
current = current.next;
}
}
}
if(!inList)
{
newNode.next = first;
first = newNode;
}
}
這裏是我的節點類如果需要的話:
public class MajorNode
{
public String majorName;
public int frequency;
public MajorNode next;
public MajorNode(String majorName, int frequency)
{
this.majorName = majorName;
this.frequency = frequency;
}
public String toString()
{
return majorName + " " + frequency;
}
}
沒有我唯一的問題是,這是否更新每個項目的頻率是否正確?謝謝大家。 – Brendan 2011-05-04 23:04:14
你100%確定你的列表沒有在某個地方得到一個循環? – 2011-05-04 23:23:26