142. Linked List Cycle II

Posted skillking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    }

 

    

以上是关于142. Linked List Cycle II的主要内容,如果未能解决你的问题,请参考以下文章

142. Linked List Cycle II

142. Linked List Cycle II

LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

142. Linked List Cycle II

142. Linked List Cycle II

142. Linked List Cycle II