用快慢指针求单链表的环的第一个节点

//求单链表的环的第一个节点,用快慢指针作
public static Node getFirstNodeInCycle(Node head){
    Node slow = head;
    Node fast = head;
    
    // 1 找到快慢指针相遇点
    while(fast != null && fast.next != null){
        slow = slow.next;
        fast = fast.next;
        if(slow == fast){
            break;
        }
    }
    
    //错误检查,这是没有环的状况
    if(fast == null || fast.next == null){
        return null;
    }
    
    //2 如今,相遇点离环的开始处的距离等于链表头到环开始处的距离,
    //这样,咱们把快慢指针放在链表头,快指针保持在相遇点,而后同速度前进,再次相遇点,
    //而后同速度前进,再次相遇点就是环的开始处。
    slow = head;
    while (slow != fast){
        slow = slow.next;
        fast = fast.next;
    }
    return fast;
}
相关文章
相关标签/搜索