思路
- 快慢指针的方法
- 定义两个引用fast,slow,初始情况下均让其指向链表的头节点,fast每次走两步,slow每次走一步
- 判断是否存在两个引用指向同一个节点相同的情况
- 若存在,存在环,反之,不存在环
代码
public class Solution10 {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
}