import java.util.*;
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
/*
HashSet<ListNode> set = new HashSet<>();
ListNode cur=head;
while(cur!=null)
{
if(set.contains(cur)) return true;
else{
set.add(cur);
}
cur=cur.next;
}
return false;
*///
//双指针版本:如果一个链表有环,那么这个环一定是从尾部发出的
//slow指针每次走一步,fast指针每次走两步,如果有环二者一定会相遇
ListNode fast=head;
ListNode slow=head;
while(fast!=null && slow!=null)
{
slow=slow.next;
if(fast.next!=null)
fast=fast.next.next;
else return false;
if(slow==fast) return true;
}
return false;
}
}