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?
Solution:
analysis on the discuss: Suppose the first meet at step K, the length of the Cycle is R. So.. 2k-k=nr,k=nrnow, the distance between the start node of the list and the start node of cycle is s. The distance between the start of list and the first meeting node are k(the pointer which wake one step at a time waked k steps). The distance between the start node of cycle and the first meeting node ism, So...s=k-m, s=nr-m= (n -1) r+ (r-m), here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the FI RST meeting node, all of them wake one step at a time, and the first time they meeting are each and the the the the cycle of the start.
/** 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*faster =Head; ListNode*slower =Head; while(Faster->next && faster->next->next) {Faster=faster->next->Next; Slower=slower->Next; if(faster==slower) {ListNode*temp=Head; while(temp!=slower) {Temp=temp->Next; Slower=slower->Next; } returntemp; } } returnNULL; }};
"Leetcode" 142-linked List Cycle II