Linked List Cycle II

本文讨论了如何在给定的链表中找出循环的起始节点,包括使用快慢指针的方法来定位相交点,以及通过将慢指针重新定位至链表头部并同时移动两个指针来确定起始点。

https://oj.leetcode.com/problems/linked-list-cycle-ii/

Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.

Follow up:
Can you solve it without using extra space?

public ListNode detectCycle(ListNode head)

这题其实是固定做法,首先先用Linked List Cycle的做法找到第一个相交点,

第二,然后把慢指针返回头指针,然后快慢指针都一步步走next,然后再找到相交点,然后就算是找到了。

给出代码:

    public ListNode detectCycle(ListNode head) {
        ListNode one_step = head, two_step = head;
        while(one_step != null && two_step != null){
            if(two_step.next == null || one_step.next == null){
                return null;
            }
            one_step = one_step.next;
            two_step = two_step.next.next;
            if(one_step == two_step)
                break;
        }
        if(one_step == null || two_step == null)
            return null;
        one_step = head;
        while(one_step != two_step){
            one_step = one_step.next;
            two_step = two_step.next;
        }
        return one_step;
    }

2018-01-21 Update:

果然不出我所料,上一次我只是记忆着答案,并没有真正的去理解它。所以我这一次思考了一下。得到了下面的解释:

假设存在环。那么假设从head到环的起点的长度为m,环自身的长度为n。第一次oneStep和twoStep相遇的时候oneStep走了k步。那么我们可以得到下面这条式子: (k - m) % n == (2 * k - m) % n。 根据这条式子我们可以知道k是可以被n整除的。所以此时twoStep所处的位置可以用-m % n表示。所以当oneStep再一次走完m这个长度到达环的起点的时候,twoStep所处的位置也会变成如下表达: (-m + m) % n = 0 % n。 也就是环的起点,所以他们这时会恰好在环的起点相遇,而他们第二次相遇的点便是环的起点。


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值