Title meaning: If there is a ring, return to the entry node.
Idea: First judge have no ring, and then calculate the knot number of the ring, then P1 point to the head, P2 back to the node, p1, p2 meet for the entrance node
PS: or the idea of using the pointer spacing
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: OneListNode *detectcycle (ListNode *head) { A if(Head==null)returnNULL; -ListNode *p1,*P2; -P1=p2=head; the intn=1; - while(p2->next&&p2->next->next) { -P1=p1->Next; -P2=p2->next->Next; + if(p1==p2) { - while(p1->next!=p2) { +P1=p1->Next; A++N; at } -P1=p2=head; - while(n--){ -P2=p2->Next; - } - while(true){ in if(P1==P2)returnP1; -P1=p1->Next; toP2=p2->Next; + } - } the } * returnNULL; $ }Panax Notoginseng};
142 Linked List Cycle II (if the linked list has loops, find the entry node)