Speed pointer - linked list problem inlet ring

Suppose the length of the non-cyclic moiety is x, the length from the start point to the meeting point of the ring is y. Length of the loop is c.
Now go slowly walked the length of the pointer must be x + n1 * c + y, go that fast pointer is twice as slow walking speed of the pointer. This means that the length of the pointer go go fast is 2 (x + n1 * c + y).

Another constraint is to go faster than that of the Pointer Pointer to walk slower walking distance must be an integer multiple of the length of the loop. According to the above formula can know 2 (x + n1 * c + y) -x + n1 * c + y = x + n1 * c + y = n2 * c.

So there are x + y = (n2-n1 ) * c, what does this mean? We interpret this mathematical formula: length + acyclic ring portion to the starting point is an integral multiple of the length of the ring between the meeting point. What does this meaning in the data structure is? Now we know that two pointers are the meeting point is the distance from the ring starting point y, and x + y is now an integral multiple of the length of the ring, which means that if they walk from the meeting point on the x to the starting point.
X-step how to walk that it? Answer: Let's start a pointer away from the head, another pointer away from the meeting point, and so the two would meet pointer to go at this time is the starting point of the x-ring steps.

/**
 * 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 f = head;
        ListNode s = head;
        while(f != null && f.next != null){
            f = f.next.next;
            s = s.next;
            if(f == s){
                f = head;
                while(f != s){
                    f = f.next;
                    s = s.next;
                }
                return f;
            }
        }
        return null;
    }
}

 

Guess you like

Origin www.cnblogs.com/mxj961116/p/11924155.html
Recommended