Sword refers to the entry node of the ring in the linked list of offer

Insert picture description here
Insert picture description here
As shown in the figure, the starting point of the linked list is a, and the entry point of the ring is b. Set two fast and slow pointers starting from a, one at a time two nodes, one at a time, then they will definitely meet in the end, assuming that the meeting point is c, Then according to the calculation, there is the distance from c to b, which is the red line in the figure, and the length is equal to a to b, so we set another pointer to point to a, let the previously set slow pointer start from c, and two people walk one step, then finally meet The point of is the entrance of the ring, which is b.


    public ListNode EntryNodeOfLoop(ListNode pHead) {
    
    
        if (pHead == null||pHead.next == null) {
    
    
            return null;
        }
        ListNode fast = pHead;
        ListNode slow = pHead;
        while (fast != null &&fast.next!=null) {
    
    
            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast) {
    
    
                ListNode slow2 = pHead;
                while (slow != slow2) {
    
    
                    slow = slow.next;
                    slow2 = slow2.next;
                }
                return slow;
            }
        }
        return null;

    }

Guess you like

Origin blog.csdn.net/AIJXB/article/details/113682077