1. 题目
2. 分析
之前刚好写过一个这题的升级版,找到环的入口
当我们需要找一个环是否存在的时候,我们可以通过快慢指针,当两者相遇则说明有环,否则没环
3. 代码
public boolean hasCycle(ListNode head) {
ListNode fast = head;
while (null != fast && null != fast.next && fast.next.next != null) {
fast = fast.next.next;
head = head.next;
if (fast == head) {
return true;
}
}
return false;
}