Linked List Cycle II
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?
https://leetcode.com/problems/linked-list-cycle-ii/
Fast and Slow pointer.
Https://leetcode.com/discuss/396/is-there-any-better-answer-for-the-linked-list-cycle-ii
Two pointers coincide with a ring.
Then point the slow pointer to the head, and the two hands each step, again coincident is the result.
1 /**2 * @param {listnode} head3 * @return {ListNode}4 */5 varDetectcycle =function(head) {6 varSlow = head, fast =head;7 while(true){8 if(Fast = = =NULL|| Fast.next = = =NULL){9 return NULL;Ten } Oneslow =Slow.next; AFast =Fast.next.next; - if(Slow = = =fast) { -slow =head; the while(true){ - if(Slow = = =fast) { - returnslow; - } +slow =Slow.next; -Fast =Fast.next; + } A } at } -};
[Leetcode] [JavaScript] Linked List Cycle II