该方法应该检查链表是否具有多个相同的条目。我尝试使用方法来检查磁头是否等于当前节点,然后使电流等于current.next
,如果磁头永远不等于电流,我的磁头等于head.next
并重新启动通过将其分配给firstNode
来获取当前值。当我尝试测试代码时,它给出了以下错误:
线程中的异常" main" LinkedBag1.hasDuplicateEntries中的java.lang.NullPointerException(LinkedBag1.java:182) java:182 is while((!head.equals(current))||(current!= null)){
不确定这意味着什么以及导致我的方法出现此错误的原因。
public boolean hasDuplicateEntries(){
Node head = firstNode;
Node current = head.next;
boolean duplicate = true;
while((!head.equals(current)) || (current != null)){
if(head.equals(current)) {
duplicate = true;
}
else{
current = current.next;
}
current = firstNode;
head = head.next;
}
return duplicate;
}
我的方法有什么问题吗?任何帮助将不胜感激。
答案 0 :(得分:1)
我认为您的问题出在head = head.next;
列表中最后一个节点的head.next
是什么?将head
设置为该值然后循环并再次检查head.equals(current)
会发生什么?
(另外,也许您已经意识到了这一点,但我认为只有重复的条目彼此相邻时,您的算法才有效。)
答案 1 :(得分:0)
不确定异常,但该方法将始终返回true,因为在初始化时将“duplicate”设置为true,并且稍后仅将其设置为true(需要“boolean duplicate = false;”)
答案 2 :(得分:0)
public boolean hasDuplicateEntries() {
int currentIndex = 0;
for (Node current = head; current != null; current = current.next) {
//with each node in list, compare it to all element of list
int nodeIndex = 0;
for (Node node = head; node != null; node = node. next) {
if (currentIndex != nodeIndex && node.equals(current)) {
return true;
}
nodeIndex++;
}
currentIndex++;
}
return false;
}
答案 3 :(得分:0)
您要删除重复元素吗?因此,您可以使用一些不能包含重复项的日期结构,例如Set。