初始状态
image.png

经过多次”移动“后的状态
image.png

如果能相遇,那么 car == bike, 也就是它们在环形链表上, car 和 bike 的地址相等。

/**
 * @Description
 * 给定一个链表,判断链表中是否有环。
 *
 * 如果链表中存在环,则返回 true 。 否则,返回 false 。
 *
 * 解决方法:快慢指针,慢的走一下 快的走两下,如果有环形链表那么他么肯定会在某一点相遇
 * @Author Meng
 * @Versions
 * @Date 2021-08-24-18:37
 */
public class Solution141 {
    public static void main(String[] args) {
        ListNode l1 = new ListNode(3);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(0);
        ListNode l4 = new ListNode(4);

        l1.next = l2;
        l2.next = l3;
//        l3.next = l4;
//        l4.next = l2;

        System.out.println(hasCycle(l1));
    }

    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null){
            return false;
        }
        ListNode quick = head;
        ListNode slow = head;
        do {
            quick = quick.next.next;
            slow = slow.next;
            if (quick == null || slow == null || quick.next == null){
                return false;
            }
        }while ((quick.next != slow.next));
        return true;
    }
}