Given a linked list, return the node where the cycle begins. If There is no cycle, return null .
Note:do not modify the linked list.
Follow up:
Can you solve it without using extra space?
Assuming head to ring position distance is a, two pointer meet distance ring start position B
2 (A + b + mcycle) = a + B + ncycle;
=>a+b = (n-m) Cycle
A = (n-m) cycle-b;
So the first two pointer meet position and head down together, the position that meet again is the cycle start point.
PublicListNode detectcycle (ListNode head) {if(Head = =NULL)return NULL; varslow =Head; varFast =Head; while(fast!=NULL&& Fast.next! =NULL) {Slow=Slow.next; Fast=Fast.next.next; if(slow = = fast) Break; } if(fast==NULL|| Fast.next = =NULL)return NULL; Slow=Head; while(Slow! =fast) {Slow=Slow.next; Fast=Fast.next; } returnslow; }
Scaling issues
Http://www.cnblogs.com/hiddenfox/p/3408931.html
In the online collection of some of the problems related to the question, the idea of a lot of open, summed up as follows:
1. What is the length of the ring?
2. How do I find the first node in the ring (that is, linked list Cycle II)?
3. How to turn a linked list into a single linked list (release ring)?
4. How can I tell if there is an intersection of two single-linked lists? How do I find the first node that intersects?
142. Linked List Cycle II