Source http://hi.baidu.com/iwitggwg/blog/index/1 is very good.
Question 1: How can we determine whether a single-link table has a ring (that is, a ring consisting of node E and node R )?
Set node * fast, * low to traverse from the starting point of the linked list at the same time. The length of each moving fast pointer is 2, and the slow pointer is 1. If there is no ring, fast cannot overlap with low after traversal, and fast or fast-> next will inevitably reach null. If there is a ring, fast will inevitably enter the ring no later than low, because the fast moving step is 2 and the low moving step is 1, fast will inevitably overlap with low (and it must be the first coincidence) a week before low enters the ring and continues loop traversal ). The function can be written as follows:
bool hasCircle(Node* head, Node* &encounter){Node *fast = head, *slow = head;while(fast && fast->next){fast = fast->next->next;slow = slow->next;if(fast == slow){encounter = fast;return true;}}encounter = NULL;return false;}
Question 2: If a ring exists, how can we find the entry point of the ring (that is, node e in )?
Q: As shown in, set the distance from the start point of the link to the entry point of the ring to X, and the distance from the entry point of the ring to the intersection point of fast and low in question 1 to y, it is also set in fast and low when fast has been round for N weeks (n> 0), and the total length of low movement is S, then the total length of Fast movement is 2 s, the length of the ring is R. Then
S + Nr = 2 S, N> 0 ①
S = x + y ②
Get S = nR from formula ①
Method ②
Nr = x + y
X = nR-y ③
Now let a pointer P1 start to traverse from the starting point of the linked list, pointer P2 start to traverse from the encounter, and the moving step sizes of P1 and P2 are both 1. Then, when P1 moves step X, that is, the entry point of the ring, it can be seen in Type 3. At this time, P2 also moves step X, that is, NR-y. Since P2 starts to move from encounter, P2 moves the NR step back to encounter, and then moves the y step back to the entry point of the ring. That is, when P1 moves step X to the entry point of the ring for the first time, P2 also happens to reach the entry point. The function can be written as follows:
Node* findEntry(Node* head, Node* encounter){ Node *p1 = head, *p2 = encounter;while(p1 != p2){p1 = p1->next;p2 = p2->next;}return p1;}