有人可以看看我的代码中是否有错误吗?我已经找了一段时间,并尝试调整东西,但我就是无法让它工作。
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"的无限循环中停止并无限增加。我很困惑。
很难确切地说出您发布的代码旨在做什么。我猜这些想法是它需要一个新单词并将其添加到列表中,或者如果它已经存在,则增加计数器。如果是这种情况,那么您的代码中有很多错误。
- 如果未找到单词,则不会添加新节点
- 如果当前节点与单词不匹配,则不会移动到下一个节点
- 在增加计数器并将节点移动到列表的头部后,您不会退出循环
我将在这里使用伪代码,并让您实现细节 - 如果含义不明显,请告诉我。
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();
}
}
由于您在找到单词后不会更改当前,因此它永远不会获得 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();
}