给定一个链表,返回链表开始入环的第一个节点。?如果链表无环,则返回?null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
说明:不允许修改给定的链表。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2*(x+n1*c+y)=x+n2*c+yx+y=(n2-n1)*c ,理解式子含义为从环中任意一点走x+y步,还能回到这点/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        // 判断有无环
        ListNode fast = head;
        ListNode slow = head;
        boolean hasCycleFlag = false;
        while (fast != null && fast.next != null) {//
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                hasCycleFlag = true;
                break;
            }
        }
        // 若无环直接返回null,否则找到环的起点并返回
        if (!hasCycleFlag) {
            return null;
        } else {
            ListNode p = head;
            while (p != slow) {
                p = p.next;
                slow = slow.next;
            }
            return p;
        }
    }
}原文:https://www.cnblogs.com/coding-gaga/p/11780360.html