【数据结构】算法 Linked List Cycle find cycle begins 环形链表II [返回环的入口节点]

Linked List Cycle find cycle begins 环形链表II [返回环的入口节点]

双指针

快慢指针,快指针一次移动2个node,慢指针一次移动1个node,

通过公式推导的结论,当快慢指针在环内相遇到的节点开始继续使用指针依次遍历到环的入口的步数等于从头结点使用指针依次遍历到环入口的节点数

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode p = head; 
        ListNode q = head;
        if(q.next==null) return null;
        do{
            p = p.next;
            q = q.next.next;
        }while(p!=q&&q!=null&&q.next!=null);

        if(q==null||q.next==null){
            return null;//确定无环
        }        
        //确定存在环
        p = head;        
        while(p!=q){
            p = p.next;
            q = q.next;
        }
        return p;
    }
}
原文地址:https://www.cnblogs.com/dreamtaker/p/14509108.html