Given a linked list, return the node where the cycle begins. If There is no cycle, return null
.
Follow up:
Can you solve it without using extra space?
The starting point of the ring in the single-linked list is the extension of the previous single-linked list to see if there is a ring in it, as in one of my previous articles (http://www.cnblogs.com/grandyang/p/4137187.html). Or to set a fast and slow pointer, but this time to record two pointers to meet the position, when two pointers meet, let its a pointer from the list Head Start, Step Two step, step by step like Minion, like the Devil's pace ... Haha, hold on. At this point the location of the link is the beginning of the ring in the list. The code is as follows:
/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode*detectcycle (ListNode *head) { if(!head | |!head->next)returnNULL; ListNode*slow =Head; ListNode*fast =Head; while(true) {Slow= slow->Next; Fast= fast->Next; if(!fast | |!fast->next)returnNULL; Fast= fast->Next; if(Fast = = slow) Break; } Slow=Head; while(Slow! =fast) {Slow= slow->Next; Fast= fast->Next; } returnFast; }};
There are many extensions to the ring problem in a single-linked list, such as the length of the loop, or how to remove the ring, and so on, see the summary of the online deity (http://www.cnblogs.com/hiddenfox/p/3408931.html).
[Leetcode] Linked List Cycle II single-linked list of rings in the second