链接列表在几次迭代后中断

时间:2014-12-16 19:32:08

标签: java linked-list

有人可以查看我的代码是否有错误?我已经寻找了一段时间,并试图调整一些东西,但我不能让它工作。

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

好的,所以这段代码运行但没有给我一个错误代码。一旦找到所需的单词,它就会陷入无限循环。整个代码是从hamlet中读取单词并将它们添加到链表中。每当一个单词已经在列表中时,我们递增它的计数器并将该链接移动到链表的开头。如果我在调试模式下跟随它,它可以正常运行大约12个字左右,然后在一个无限循环中停止,单词" i"并且无限地增加。我很困惑。

2 个答案:

答案 0 :(得分:0)

由于您在找到单词后没有更改当前内容,因此它永远不会获得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();
  }

答案 1 :(得分:0)

很难确切地说出您发布的代码的目的是什么。我猜这个想法是它需要一个新单词并将其添加到列表中,或者如果计数器已经存在则递增计数器。如果是这种情况,则代码中会出现相当多的错误。

  1. 如果找不到该字词,您就不会添加新节点
  2. 如果当前节点与单词
  3. 不匹配,则您无法移动到下一个节点
  4. 在递增计数器并将节点移动到列表头部后,您没有退出循环
  5. 我在这里使用伪代码并让您实现细节 - 如果含义不明显,请告诉我。

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