链表中环的问题
给定一个链表,判断链表中是否有环
图解
示例
* 输入:head=[3,2,0,-4] pos=1 * 输出:true * 解释:链表中有一个环,其尾部连接到第二个节点
思路
判断是否有环,最容易的是使用哈希,遍历的时候将元素放入到set(或者map)中,如果有环,就一定会发生哈希碰撞,这个碰撞的位置就是环入口的位置
代码实现
/**
* 题目:给定一个列表,判断是否有环
* 示例:
* 输入:head=[3,2,0,-4] pos=1
* 输出:true
* 解释:链表中有一个环,其尾部连接到第二个节点
* @param head
* @return
*/
public Node detectCircle(Node head){
Node pos = head;
Set<Node> hash = new HashSet<>();
while (pos != null) {
if (hash.contains(pos)){
return pos;
}else {
hash.add(pos);
}
pos = pos.next;
}
return null;
}