给定一个链表,返回链表开始入环的第一个节点。 若是链表无环,则返回 null。网络
为了表示给定链表中的环,咱们使用整数 pos 来表示链表尾链接到链表中的位置(索引从 0 开始)。 若是 pos 是 -1,则在该链表中没有环。指针
说明:不容许修改给定的链表。code
来源:力扣(LeetCode)
连接:https://leetcode-cn.com/problems/linked-list-cycle-ii
著做权归领扣网络全部。商业转载请联系官方受权,非商业转载请注明出处。索引
2*(x+n1*c+y)=x+n2*c+y
x+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; } } }