Double pointer:
Use two pointers fast and slow, both of which start at the head of the linked list.
The slow moves backward one position at a time, while the fast pointer moves two positions at a time.
If there is a ring in the linked list, the fast pointer will eventually meet the slow pointer in the ring.
prove:
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(slow!=null&&fast!=null&&fast.next!=null&&fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(fast==slow){
return true;
}
}
return false;
}
}