码迷,mamicode.com
首页 > 其他好文 > 详细

142. Linked List Cycle II

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

标签:start   图片   http   slow   als   head   return   fir   fast   

一、题目

  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

标签:start   图片   http   slow   als   head   return   fir   fast   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!