Java 链表在几次迭代后中断

Java 链表在几次迭代后中断,java,linked-list,Java,Linked List,有人能看看我的代码中是否有错误吗?我已经找了一段时间,试着调整一些东西,但我就是不能让它工作 while(current != null) { comparisons++; String currentWord = current.getWord(); if(currentWord.equals(word)) { int count = current.getCount(); count++; current.setCount(count); i

有人能看看我的代码中是否有错误吗?我已经找了一段时间,试着调整一些东西,但我就是不能让它工作

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停止,并以不确定的方式递增。我很困惑。

因为你在找到单词后不改变当前值,所以它永远不会得到零链接,而且它总是有currentWord.equalsword返回true 尝试:


很难说清楚您发布的代码的目的是什么。我猜它的想法是,它接受一个新词并将其添加到列表中,或者如果它已经存在,则增加计数器。如果是这样的话,那么您的代码中有相当多的错误

如果找不到单词,则不会添加新节点 如果当前节点与单词不匹配,则不会移动到下一个节点 在递增计数器并将节点移动到列表的开头之后,您不会退出循环 我将在这里使用伪代码,让您来实现细节——如果含义不明显,请告诉我

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();
    }
}

它怎么断的?准确的错误/堆栈跟踪是什么?是否有可以显示的错误?您可能还需要提供更多的代码,例如getLink做什么?问题也可能出在您的链表实现中…您遇到了什么错误?这段代码的哪一行?您确定您的变量是运行此代码段时应该使用的变量吗?试着提供一个你的代码想做什么?这仍然没有帮助。因此,代码退出循环,并从我的main方法再次调用,以将下一个单词添加到列表中。
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();
    }
}