链表环路检测

给定一个有环链表,实现一个算法返回环路的开头节点。
有环链表的定义:在链表中某个节点的next元素指向在它前面出现过的节点,则表明该链表存在环路。
链表有环理解:如果链表中有环,那么快慢指针就一定可以相遇,此时快指针移动的距离是慢指针的两倍
题解:1.检测有没有环,使用快慢指针slow和fast(一次走两步);
      2.找位置,当找到环之后,slow从head出发,fast从相遇点出发,一次都走一步,再次相遇为环的入口点
public class detectCycle {

    public static ListNode detectCycle(ListNode head){
        if (head==null||head.next==null){
            return null;
        }
        ListNode slow=head;
        ListNode fast=head;
        //找到环入口
        while (fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            if (slow==fast){
                break;
            }
        }
        if (fast==null||fast.next==null){
            return null;
        }
        //让其中一个指针从头开始走,另一个指针从环处开始走,再次相遇时即为环的入口
        slow=head;
        while (fast!=slow){
            fast=fast.next;
            slow=slow.next;
        }
        return slow;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30926503/article/details/107506467