给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

    为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

    分析:面试常考题!不仅需要把环找出来,还要找到环的入口!一开始做这道题可能会有些懵,但是用数学分析的方法分析一下,就会明了起来,证明过程较复杂,先不写了,等有空细说。

    参考代码:
    public class Solution {
    public ListNode detectCycle(ListNode head) {
    ListNode slow=head,fast=head;
    while(fast!=null&&fast.next!=null){
    fast=fast.next.next;
    slow=slow.next;
    if(fast==slow) break;
    }
    if(fast==null||fast.next==null) return null;
    slow=head;
    while(fast!=slow){
    fast=fast.next;
    slow=slow.next;
    }
    return slow;
    }
    }