快慢指针 | 环形链表

public boolean isCircle() {
        if(first == null || first.next == null) return false;
        Node<U> slow = first;
        Node<U> fast = first.next;
        int i = 1;
        while (fast != null && fast.next != null) {
            if(fast.equals(slow)) {
                System.out.println("开始结束:"+(i++)+",slow="+slow.unit+",fast="+fast.unit);
                return true;
            }
            System.out.println("开始循环:"+(i++)+",slow="+slow.unit+",fast="+fast.unit);
            slow = slow.next;
            fast = fast.next.next;
        }

        return false;
    }

这个代码是判断是否环形链表的方法,一定会相遇,因为它们的距离每一次执行完后fast与slow就减1,最终为0相遇。当链表如下时,代码运行输出:

 

输出:

开始循环:1,slow=0,fast=1

开始循环:2,slow=1,fast=3

开始循环:3,slow=2,fast=5

开始循环:4,slow=3,fast=1

开始循环:5,slow=4,fast=3

开始结束:6,slow=5,fast=5

true

原文地址:https://www.cnblogs.com/zjazn/p/15309497.html