First, the topic
1, examining
2. Analysis
Given a list, if no ring returns NULL, if there is a ring, return the node where the ring begins.
Second, the answer
1, Ideas:
Method One,
//a B//start------->-------->meeting//| | //<----------//C//assume fast and slow meets at K steps//k=a+b+r1 (b+c) Slow runs R1 cycles//2K=A+B+R2 (b+c) Fast runs R2 cycles//2k=a+b+r2 (b+c) =2a+2b+2r1 (b+c)//( b+c) (r2-2r1) =a+b = (b+c) n=a+b//a= (n-1) b+nc= (n-1) (b+c) +c which means when slow moves (n-1) cycles and C, start moves a PublicListNode detectcycle (ListNode head) {if(Head = =NULL|| Head.next = =NULL) return NULL; ListNode First=Head; ListNode Second=Head; BooleanIscycle =false; while(First! =NULL&& Second! =NULL) { First=First.next; if(Second.next = =NULL) return NULL; Second=Second.next.next; if(First = =second) {iscycle=true; Break; } } if(!iscycle)return NULL; First=Head; while(First! =second) { First=First.next; Second=Second.next; } returnFirst ; }
142. Linked List Cycle II