首页 > 其他 > 详细

142. Linked List Cycle II

时间:2018-10-11 23:14:22      阅读:163      评论:0      收藏:0      [点我收藏+]

一、题目

  1、审题

  技术分享图片

 

  2、分析

    给出一个链表,如果没有环则返回 null, 若存在环,返回环开始的节点。

 

二、解答

  1、思路:

    方法一、

    

    //      a        b 
    //start ------->-------->meeting
    //          |        |
    //          <----------
    //               c
    //assume fast and slow meets at k steps
    //k=a+b+r1(b+c) slow runs r1 cycles
    //2k=a+b+r2(b+c) fast runs r2 cycles
    //2k=a+b+r2(b+c)=2a+2b+2r1(b+c)
    //(b+c)(r2-2r1)=a+b => (b+c)n=a+b
    //a=(n-1)b+nc=(n-1)(b+c)+c which means when slow moves (n-1) cycles and c, start moves a

    public ListNode detectCycle(ListNode head) {
        
        if(head == null || head.next == null)
            return null;
        
        ListNode first = head;
        ListNode second = head;
        boolean isCycle = false;
        
        while(first != null && second != null) {
            
            first = first.next;
            if(second.next == null)
                return null;
            
            second = second.next.next;
            if(first == second) {
                isCycle = true;
                break;
            }
        }
        
        if(!isCycle)
            return null;
        
        first = head;
        while(first != second) {
            first = first.next;
            second = second.next;
        }
        return first;
    }

 

    

142. Linked List Cycle II

原文:https://www.cnblogs.com/skillking/p/9775490.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!