Solution One:
If there are N nodes in the linked list, the pointer P1 moves forward n on the list, and the two pointers move forward at the same speed.
When the second pointer points to the entry node of the ring, the first pointer moves around the ring and back to the entry node.
So the first thing to do is to get the number of nodes in the ring.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {public:listnode* Meetnode (listnode* head) {listnode*slow = Head,*fast=head; while (Fast&&fast->next) {slow=slow->next; fast=fast->next->next; if (slow==fast) return fast; } return NULL; } ListNode *detectcycle (ListNode *head) {listnode* Mnode = Meetnode (head); if (mnode==null) return NULL; int numofcycle=1; listnode* p = mnode; while (P->next!=mnode) {p=p->next; numofcycle++; } listnode* P2=head,*p3=head; for (int i=0;i<numofcycle;i++) p2=p2->next; while (P2!=P3) {p2=p2->next; p3=p3->next; } return p2; }};
Solution Two:
Because fast each walk 2 steps, slow each walk 1 steps, then meet when assume at the K node, then fast walked 2K step.
Set the circle size to N, then fast should go more M-circle, that is, m*n nodes. So 2k-k=m*n==>k=m*n; actually M is not 1 does not affect the final result,
I make the pointer slow point to the chain header, and then two pointers go one step at a time, so it is known that the distance between fast and slow is M-lap, and when slow goes to the entrance,
Fast is sure to meet at the entrance because of the M-ring.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode* Meetnode (listnode* head) { listnode*slow = Head,*fast=head; while (Fast&&fast->next) { slow=slow->next; fast=fast->next->next; if (slow==fast) return fast; } return NULL; } ListNode *detectcycle (ListNode *head) { listnode* mnode=meetnode (head); if (mnode==null) return NULL; listnode* p = head; while (P!=mnode) { p=p->next; mnode=mnode->next; } REUTRN p; }};
142. Linked List Cycle II