快指针每次两步,慢指针每次一步,有环则必相遇。
终止条件:null,单个节点,两个结点,都不可能有环!
public boolean hasCycle(ListNode head) { if(head==null||head.next==null||head.next.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; }