Problem: If a ring exists in a single-linked list, the starting position of the loop is
Solution: In the previous article, use the Chase method to determine whether a single-linked list exists in the ring. To find the starting position of the ring, the relationship between the length of the single linked list and the length of the ring needs to be solved. If the relationship between the length of the single-linked list and the length of the ring is determined, then the starting position of the ring is apparent.
In judging the single linked list there are two pointers p and q,p each step forward two steps, q each time before further, p speed is twice times the Q. Set the length of the single-linked list is L, the length of the ring is R, the distance from the beginning of the chain to the beginning of the ring is X, when P and Q meet, the slow pointer took a total of S step, in the ring a total of a step, the fast pointer a total of 2S steps, at this time to meet: 2s=s+n*r, so
S=x+a;
X+a= (n-1) *r+r= (n-1) *r+l-x
x= (n-1) *r+l-x-a
where (n-1) *r+l-x represents the location of the encounter, L-x represents the length of the ring, L-x-a represents the distance between the point of arrival and the starting position of the ring. That is, the distance from the starting point of the list to the beginning of the ring is equal to the distance from the location to the ring starting point. This conclusion is the theoretical basis for solving this problem. When the speed pointer encounters, let the fast pointer p again point to the start position of the list, reset the speed of P and q the same speed, when P and Q meet again when the position of the ring is the beginning of the position. The specific implementation code is as follows:
1Linknode *circlestart (Linknode *head)2 3 {4Linknode *p,*Q;5p=q=head;6 while(p! =NULL&& p->next!=NULL)7 {8P=p->next->Next;9Q=q->Next;Ten if(p==q) One Break; A } - if(P==q &&p!=NULL) - { thep=head; - while(p!=q) - { -P=p->Next; +Q=q->Next; - } + returnp; A } at Else{ - return NULL; - } -}
If the single-linked list has a ring, the starting position of the ring is obtained