// 环形链表-hash-快慢指针
// 输入:head = [3,2,0,-4], pos = 1
// 输出:true
// 解释:链表中有一个环,其尾部连接到第二个节点。
public boolean hasCycle(ListNode head){
HashSet<ListNode> set = new HashSet<>();
while (head!=null){
if(!set.add(head)){
return true;
}
head=head.next;
}
return false;
}
public boolean hascyc(ListNode head){
if(head==null||head.next==null)
return false;
ListNode slow=head;
ListNode fast=head.next;
// 会相遇才有环
while (slow!=fast){
if(fast==null||fast.next==null){
return false;
}
slow=slow.next;
fast=fast.next.next;
}
return true;
}