快慢指针,如果有环,两指针一定会相遇
注意:
①空链表和一个元素的链表直接返回false
②如果没环,快指针一定会先到null,所以只需判断快指针是否为null
③注意空指针异常,快指针的next也要判断是否为null
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return false;
ListNode slow = head;
ListNode fast = head;
while(fast!= null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}
}