双指针:
使用两个指针fast和slow,它们起始都位于链表的头部。
slow每次向后移动一个位置,而fast指针每次移动两个位置。
如果链表中存在环,则fast指针最终再与slow指针在环中相遇。
证明:
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;
}
}