Title link: the list entry ring node
Meaning of the questions: to a list, if containing ring, find the entry node ring of the list, otherwise the output null.
Solution: We set up two pointers, a fast walk, a slow you down. If there is a ring, the pointer will meet speed.
Further, a scratch two hands go, a meeting point go away, and finally an inlet in the ring will be met.
So let's find a number of links point, let go fast pointer c point of a link, you can find the node ring entrance.
Code:
1 /* 2 struct ListNode { 3 int val; 4 struct ListNode *next; 5 ListNode(int x) : 6 val(x), next(NULL) { 7 } 8 }; 9 */ 10 class Solution { 11 public: 12 ListNode* EntryNodeOfLoop(ListNode* pHead){ 13 //快指针和慢指针 14 ListNode* fast = pHead,*slow=pHead->next; 15 while(fast!=slow && fast!=NULL && slow != NULL){ 16 slow = slow->next; 17 fast = fast->next; 18 if(fast!=NULL) fast = fast->next; 19 } 20 //链表环节点个数 21 int cnt = 1; 22 ListNode *node = fast->next; 23 if(fast == slow && fast!=NULL){ 24 while(node != fast){ 25 node = node->next; 26 cnt++; 27 } 28 } 29 else return NULL; 30 31 fast = pHead;slow = pHead; 32 //fast先走cnt 33 for(int i = 0; i < cnt; i++) fast = fast->next; 34 //找到入口 35 while(fast != slow){ 36 fast = fast->next; 37 slow = slow->next; 38 } 39 return fast; 40 } 41 };