Entry node (to prove safety offer_23) the list loop

Title Description


Ring containing a linked list, find the entry ring node list. Requirements can not use the extra space.

Problem-solving ideas


Double pointer, a pointer to the fast movement of the two nodes each fast, slow a slow pointer each time a mobile node. Because the presence of a ring, the two pointers must be met in one of the nodes on the ring.

Ring entry node is assumed that y1, where the node is met z1.

Suppose fast fast pointer in the circle around the ring N, the total path length of x + Ny + (Ny) z. z is (N-1) times the speed because the pointer has been met in the last z1 nodes do not need to walk back up.

Slow and slow pointer total path length of x + y.

Twice as fast as the pointer is a pointer slow, therefore x + Ny + (N-1) z = 2 (x + y).

We are looking for a ring entry node y1, can be seen as looking for the value of the length x, we first decomposed equivalent to the above and related x: x = (N-2) y + (N-1) z.

The above is not equivalent strong law, but we can find + z is the total length of the ring y, we will then break the above equation: x = (N-2) (y + z) + z.

The left side of this equation is the length from the start point x1 to y1 ingress node of the ring, while the right is through (N-2) the rings in the ring, and from the meeting point and then through a length z1 is the length of z. At this point we can see that if at the same time to have two pointers from the beginning of the meeting point x1 and z1, a time through a distance, then finally they will meet in the ring entry node.

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

Guess you like

Origin www.cnblogs.com/ziytong/p/12123798.html