Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
With two pointers fast and slow,fast each step, slow each step, if fast catch up with slow there is a ring, otherwise does not exist.
1 BOOLHascycle (ListNode *head)2 {3ListNode *slow = head, *fast =head;4 while(Fast! =NULL)5 {6slow = slow->Next;7Fast = Fast->Next;8 if(Fast! =NULL)9Fast = Fast->Next;Ten if(Fast! = NULL && Fast = =slow) One return true; A } - - return false; the}
The Linked List Cycle II is the node that asks for the ring to appear.
When fast catches up with slow, fast is more than slow go nc,n>=1, C is the circumference of the circle. Such as:
Slow walking distance: LenA + x,fast walk: LenA + NC + x
Because Fast walk is twice times the distance of Slow: 2 (LenA + x) = LenA + NC + x
Thus, NC = LenA + x, i.e. LenA = Nc-x.
Then meet, let slow point to head,fast and slow walk the same step, and finally meet in the join place.
1ListNode *detectcycle (ListNode *head)2 {3ListNode *fast = head, *slow =head;4 5 while(Fast! =NULL)6 {7slow = slow->Next;8Fast = Fast->Next;9 if(Fast! =NULL)TenFast = Fast->Next; One if(Fast! = NULL && Fast = =slow) A Break; - } - the if(Fast = =NULL) - returnNULL; - -slow =head; + while(Slow! =fast) - { +slow = slow->Next; AFast = Fast->Next; at } - - returnslow; -}
Leetcode. Linked list cycle && Linked list Cycle II