Linked List Cycle II

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

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

 

 

给定链表,若存在环返回环的起点,否则返回null。

 

    貌似网易面试的时候曾经出过类似问题,但网易只要求判断是否存在环。具体方法为定义两个指针one 、two遍历链表,one一次扫描一个节点,two一次扫描两个节点。

若存在环最终one 和two一定会相遇。我称之为步差法,假设one访问到环的起始节点Y时two在按顺时针离Y c个节点处Z,则在经过c次前进后one、two一定会相遇于W。此时one走了c步<Y,W> 长为c,而two走过了2C步比one多走C步刚好赶上one与之重合。

      步差法就是在存在回路的情况下,不同指针每步相差K个节点,则走的快的最终会追上走的慢的,假设走了M步则他们相差K*M个节点。

 

本题是上述的扩展。可知当one和two在z点相遇时one走过a+b各节点,two走过a+b+c+b各节点,二two走过的路程是one的两倍即2*(a+b)=a+b+c+b,可知a=c。

所以本体解法,只需先让one、two以各自步长走,当one、two相遇时,two步长变为1,one从头X开始走则one、two再次相遇的点必定是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 one = head;
        ListNode two = head;
       
        while(two != null)
        {
            one = one.next;
            two = two.next;
            if(two != null)two = two.next;
           
            if(one == two)break;
        }
       
        if(two == null)return null;
       
        one = head;
       
        while(true)
        {
            if(one == two)return one;
            one = one.next;
            two = two.next;
        }
       
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值