142. Linked List Cycle II

一、题目

  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;
    }

    

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