Topic:
Find the "entrance" of the ring in the single-linked list.
Solution steps:
1, with the speed of the pointer to determine whether there is a ring (slow hands walk a step, fast hands walk two steps). If there is a ring continuation of the following calculation, if it does not exist then return to nullptr;
2, record the speed of the pointer meet the node N0.
3, a pointer from the link Table head node, another pointer from N0, "synchronous forward", the meeting node is the "entrance" of the ring.
Analysis:
Because the speed pointer is the same as the "steps", but the fast pointer each step is twice times the slow pointer, so the speed of the pointer in N0 meet, the fast pointer distance is twice times the slow pointer, namely:
S=LENGTH+NS*R+S0 (1)
2S=LENGH+NF*R+S0 (2)
In the formula, S is the distance of the slow pointer, R is the length of the ring, S0 is the distance from the ring inlet to N0, NS is the number of laps of the slow pointer in the ring, and NF is the number of laps that the fast pointer loops around.
(2) type minus (1) type, can get
S= (Nf-ns) *r, of which Nf>ns
Visible S is a multiple of R! Assuming that s=k*r,k is a positive integer, the surrogate (1) formula can be
length+s0= (K-ns) *r, so that j= k-ns,j is a positive integer.
Visible Length+s0 is also a multiple of R! The distance of the known node n0 to the ring inlet is R-S0,LENGTH=J*R-S0.
Make a pointer from the node of the linked list head, another pointer from N0, "synchronous forward", will inevitably meet at a certain point. When J=1, Length=r-s0, obviously meet the node is the ring entrance. When J>1, still meet at the ring entrance, think about why?
"Single-linked list" finds the "entrance" of a single-linked table ring