【发布时间】:2017-07-07 13:05:16
【问题描述】:
我正在使用 hashmap 在链表中编写用于 lop 检测的代码。为什么会无限循环?
boolean hasCycle(Node head) {
HashMap<Integer,Node> map = new HashMap<Integer,Node>();
//<Address,data>
if(head == null || head.next == null)
return false;
Node p = head;
while(p.next!=null)
{
if(map.containsValue(p.next))
{
return true;
}
else
{
map.put(p.data,p.next);
}
p = p.next;
}
return false;
}
【问题讨论】:
-
你为什么用
HashMap而不是HashSet? -
能否提供测试数据
-
ericlippert.com/2014/03/05/how-to-debug-small-programs -- 向鸭子解释为什么它应该不无限循环。如果这没有帮助,请使用调试器并单步执行。当它做了你没想到的事情时,你就发现了问题。
-
对于简单的情况,它看起来没有错。测试数据会很好。
-
@parimal 如果您希望我们能够为您提供帮助,您必须提供Minimal, Complete, and Verifiable example,否则您的问题将被关闭为“无法再复制的问题”。
标签: java linked-list hashmap