[英]Linked List breaks after a few iterations
有人可以看看我的代碼中是否有錯誤? 我已經尋找了一段時間,並嘗試進行調整,但我無法使其正常運行。
while(current != null)
{
comparisons++;
String currentWord = current.getWord();
if(currentWord.equals(word))
{
int count = current.getCount();
count++;
current.setCount(count);
isFound = true;
total++;
LLNode next = current.getLink();
previous.setLink(next);
current.setLink(top);
top = current;
}
else
{
previous = current;
current = current.getLink();
}
}
好的,這段代碼可以運行,但是不會給我一個錯誤代碼。 只要找到需要的單詞,它就會陷入無限循環。 整個代碼是從小村庄讀取單詞並將它們添加到鏈接列表中。 每當列表中已經有一個單詞時,我們就會增加它的計數器並將該鏈接移到鏈接列表的開頭。 如果我在調試模式下遵循它,則它可以正常運行約12個單詞左右,然后僅在單詞“ i”的無限循環中停止並無限地遞增。 我很困惑
由於您在找到單詞后沒有更改電流,因此它將永遠不會獲得nil鏈接,並且始終具有currentWord.equals(word)返回true嘗試:
if(currentWord.equals(word))
{
int count = current.getCount();
count++;
current.setCount(count);
isFound = true;
total++;
LLNode next = current.getLink();
previous.setLink(next);
current.setLink(top);
top = current;
current = next; //add this line
}
else
{
previous = current;
current = current.getLink();
}
很難確切說明您發布的代碼打算做什么。 我猜想這個想法是,它需要一個新詞並將其添加到列表中,或者如果已經存在則增加計數器。 如果真是這樣,那么您的代碼中就會有很多錯誤。
我將在這里使用偽代碼,讓您實現細節-如果含義不明顯,請告訴我。
Node current = top;
boolean found = false;
boolean added = false;
while (!(found || added)) {
if (current matches word) {
increment current.count and move to top of list;
found = true;
} else if (current.getLink() == null) {
make new node using word, count 1, link null;
current.setLink(new node);
added = true;
} else {
current = current.getLink();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.