LeetCode(142):Linked List Cycle II

Linked List Cycle II:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

题意:对于给定的一个链表,判断其是否有环,如果有环的话,返回环开始的结点。

思路:在I中是判断是否有环,采用快慢指针的方法可以进行判断。此题利用了从头结点到环开始的路程=从相遇到环开始的路程。证明可以参考这里。因此,可以将快慢指针相遇时,慢指针指向头结点,然后快指针和慢指针分别都走一步,直到两者再次相遇,则相遇的地方就是环开始的地方。

代码:

public ListNode detectCycle(ListNode head) {
        if(head==null)return null;
         ListNode fast = head;
         ListNode slow = head;
         while(fast!=null){
             if(fast!=null)
                 fast = fast.next;
             if(fast!=null)
                 fast = fast.next;
             if(slow!=null)
                 slow = slow.next;
             if(fast!=null && fast==slow){
                 slow = head;
                while(slow!=fast){
                    slow = slow.next;
                    fast = fast.next;
                }
                return slow;
             }
         }
            return null;
        
    }
原文地址:https://www.cnblogs.com/Lewisr/p/5140229.html