环状链表的入环节点

快指针每次走两步。慢指针每次走一步。
相遇的时候 肯定在环中。

这个时候最简单的办法就是在围绕环来一圈 算出count。
求出了环的大小n

这个时候两个都从起点开始。一个先走n,另一个再开始走。相遇在入口

下面是一种比较简单的写法,但是不是很好理解。 假设快的比满的只多走了一圈 很好解释。 如果是多圈呢? 就需要严谨的数学证明了

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */


public class Solution {
    /*
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. if there is no cycle, return null
     */
    public ListNode detectCycle(ListNode head) {
        // write your code here
        ListNode slow = head;
        ListNode fast = head;
        if(head == null||head.next == null){
            return null;
        }
        if(head.next.next == head){
            return head;
        }
        while(fast.next !=null&&slow.next != null){
            if(fast.next.next == null){
                return null;
            }
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                ListNode slownew = fast;
                ListNode fastnew = head;
                while(slownew!=fastnew){
                    slownew = slownew.next;
                    fastnew = fastnew.next;
                }
                return fastnew;
            }
        }
        return null;
    }
}
原文地址:https://www.cnblogs.com/tobemaster/p/7914655.html