2019-05-28 leetcode 142. Linked List Cycle II 寻找带环链表开始环的地方

10369851-49c0db7d2438c6e2.png
屏幕快照 2019-05-28 下午10.43.57.png

解释


10369851-7631e718a24770f5.jpg
6001559055056_.pic.jpg

当我们通过slow和fast碰撞得出他是有环的,这时候开始节点到loop的距离x1,等于他们相遇节点到loop开始的节点(距离为x3)
我们在开始节点和相遇节点,创建两个节点,一次走一步,最终会相遇在loop开始的地方
fast跑的距离为:x1+x2+x3+x2+m(x3+x2) m代表跑了多少圈 你也去好奇为什么会额外有个(x2+x3),因为fast为了跟slow碰撞,他始终要循环一圈回来碰撞
slow跑的距离为:x1+x2+n(x2+x3) n代表跑了多少圈
fast = 2slow 则 x1+x2+x3+x2+m(x3+x2) = 2(x1+x2+n(x3+x2))
x2+x3 m(x3+x2) = x1+x2+2n(x3+x2)
x3 + ?(x3+x2) = x1 //这里我们不管他跑了多少圈,总之剩下x3和x1的距离到loop开始的点是一样的,两边一起跑就会相遇在该点

public class Solution {
        public ListNode detectCycle(ListNode head) {
            ListNode slow = head;
            ListNode fast = head;
            Boolean isCircle = false;
            while (fast!=null&&fast.next!=null)
            {
                slow = slow.next;
                fast = fast.next.next;
                if (slow == fast)
                    isCircle = true;
            }
            if (isCircle == false)
            {
                return null;
            }
            ListNode start = head;
            while (slow != start)
            {
                slow = slow.next;
                start = start.next;
            }
            return start;
        }
    }

转载于:https://www.jianshu.com/p/d968a2f2cff4

猜你喜欢

转载自blog.csdn.net/weixin_34304013/article/details/91106921