StackOverflowers。
我对这个网站很陌生,并且认为明智的做法是来这里寻求一些有关涉及从链接列表打印正确输出的特定问题的帮助。 这个想法是采用一个使用数组生成列表的程序并将其转换为链接列表,同时实现相同的结果。现在,我已经为此花费了几个小时,尽管我已经达到了实际打印输出的程度(最终),但仍未获得所需的结果。
需要结果:
注意:此结果是使用数组生成的
单词:本次计数:2
单词:类(class)数:2
单词:检查次数:1
单词:计数:7
字数: build 数量:1
字数: 数: 9
单词:算法计数:4
字数: 数: 9
我得到的结果:
注:此结果是数组方式转换为链表时产生的
单词:信念数:2
单词:我的数量:2
字数: 数: 2
单词:最多计数:2
单词:计数:2
字数: 计数:2
字数: 计数: 2
字数:事实数:2
单词:计数:2
我不太清楚为什么会出现这种情况,而且我似乎无法追踪它。我尝试过阅读笔记并进行搜索,但无济于事。我不确定它是否与 setNext(...) [Node 类的一部分] 或我在哪里调用 IncrementCount() 方法 [Word 类的一部分] 有关。我不相信 setNext(...) 甚至有一个目的,而只是代码的一部分,此时什么也不做。
我希望我的交付不会偏离轨道,并且可以为我的尝试提供解决方案。我知道我已经达到了极限,因为我无法想到与此相关的任何其他事情。
期待您的建议。
谢谢。
T3。
private Node top;
public WordList()
{
top = null;
}
// This method adds words to the linked list.
public void addWord( String w )
{
Word word = new Word( w );
top = new Node(word,top);
// Checks to see if a particular word is present more than once.
// If the particular word is encountered more than once, it
// increments the word count for that particular word, else
// a new node is created to store another word. The word check
// process is repeated once more.
// Note: getWord() is part of the Node class that attempts to retrieve
// a word that is held in a particular node.
// matchesWord(...) determines whether a particular word (string) has been
// encountered. If result is true, the number of times
// the word is encountered should be incremented.
if( top.getWord().matchesWord( w ))
{
top.getWord().incrementCount();
}
else
{
Word newWord = new Word ( w );
Node newNode = new Node(newWord, top);
//top = newNode;
top.setNext(newNode);
}
} // end addWord
// This method prints out the linked list.
public void printList()
{
Node currentNode;
currentNode = top.getNext();
while(currentNode != null)
{
System.out.println(currentNode.getWord());
currentNode = currentNode.getNext();
}
}
最佳答案
我可以立即看到一些问题:
- 除非
getWord()
方法做了一些相当奇怪的事情,否则它只会在第一个单词与新添加的单词匹配时增加计数 - 无论是否存在匹配项,您都会将新的
节点
添加到列表的头部 - 结合第一个问题,所有内容的计数均为 2 - 在
printList()
中,您需要从top
开始,而不是top.getNext()
关于java - 链接列表输出未正确生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8336419/