[英]Add method in LinkedList is not working
我正在研究这个作为我的Java类的额外练习,但我似乎无法理解为什么我的add方法不起作用。 我已尝试逐行调试代码,但我无法看到它出错的地方。 这显然是一个逻辑错误。 当我测试add方法时,它似乎工作但它没有正确地连接Node我猜,或者没有存储数据。
因此,分配是编写链表(不添加重复项)。 我将Node类作为LinkedSet类的内部函数。 我们的教科书建议针对这一特定任务。 这是我正在使用的添加方法。
public class LinkedSet <T> implements SetInterface <T> {
private Node firstNode;
private int numberOfEntries;
public LinkedSet (){
firstNode = null;
numberOfEntries = 0;
}
public boolean add(T newEntry){
boolean result = false;
Node aNewNode = new Node (newEntry);
//If Node is currently null then add data to front
if(firstNode == null)
firstNode = aNewNode;
else
{
//Add newEntry if it's not already stored.
if(!contains(newEntry) && numberOfEntries != 0)
{
aNewNode.next = firstNode;
firstNode.next = aNewNode;
firstNode = aNewNode;
result = true;
}
else
result = false;
}
return result;
}//End add
public boolean contains(T anEntry){
boolean found = false;
while (!found && (firstNode != null))
{
if(anEntry.equals(firstNode.getData()))
found = true;
else
firstNode = firstNode.getNextNode();
}
return found;
}
private class Node {
private T data;
private Node next;
private Node (T theData){
data = theData;
next = null;
}
private Node(T theData, Node nextNode){
data = theData;
next = nextNode;
}
} //End Node class
}End LinkedSet
此外,这是添加的测试方法(需要编写单独的测试应用程序并在单独的主类中完成)
private static boolean testAdd(SetInterface<String> aSet, String[] contentsToAdd){
boolean result = false;
for (int index = 0; index < contentsToAdd.length; index++)
{
aSet.add(contentsToAdd[index]);
result = true;
}
return result;
}//End testAdd
还有一些其他的方法,但是直到我可以使add方法工作,我不能对它们做太多,所以我很确定这个问题就在这里。 我在类似的问题上环顾网络,但我仍然看不到它在哪里。 任何帮助表示赞赏,我现在已经搞砸了太久了。
if(firstNode == null)
firstNode = aNewNode;
在这种情况下你应该返回true
。
if(!contains(newEntry) && numberOfEntries != 0)
这个测试没有多大意义。 反过来会更有意义:
if(numberOfEntries != 0 && !contains(newEntry))
因为没有条目调用contains()
如果没有条目,但contains()
已经知道无论如何,如果numberOfEntries
为零,则firstNode
为null,所以它应该只是
if (!contains(newEntry))
注意:您没有维护numberOfEntries
。
我没有彻底阅读你的所有代码,但这里有一个错误:
if(firstNode == null)
firstNode = aNewNode;
它应该增加numberOfEntries
。
因为numberOfEntries
始终为零,并且add无法正常工作
同样,您也不会在else
维护numberOfEntries
。
包含方法也有问题,您正在更改firstNode引用,您不应该更改它
public boolean contains(T anEntry){
boolean found = false;
Node ptr = firstNode;
while (!found && (ptr != null))
{
if(anEntry.equals(ptr.getData()))
found = true;
else
ptr = ptr.getNextNode();
}
return found;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.