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/
快慢指针。
https://leetcode.com/discuss/396/is-there-any-better-answer-for-the-linked-list-cycle-ii
两个指针重合说明有环。
然后把慢指针指向head,双指针每次走一步,再次重合就是结果。
1 /** 2 * @param {ListNode} head 3 * @return {ListNode} 4 */ 5 var detectCycle = function(head) { 6 var slow = head, fast = head; 7 while(true){ 8 if(fast === null || fast.next === null){ 9 return null; 10 } 11 slow = slow.next; 12 fast = fast.next.next; 13 if(slow === fast){ 14 slow = head; 15 while(true){ 16 if(slow === fast){ 17 return slow; 18 } 19 slow = slow.next; 20 fast = fast.next; 21 } 22 } 23 } 24 };
时间: 2024-10-07 06:00:16