单链表中的环二。题意是给一个链表,如果这个链表中有环,请return环的起点;若没有,return null。找是否有环可以参照[LeetCode] 141. Linked List Cycle的讲解。至于怎么找到环的起点,我这里引用一个非常好的讲解,https://www.cnblogs.com/hiddenfox/p/3408931.html
因为快慢指针的速度是一个2步一个1步,所以当两个指针相遇的时候,fast走过的长度一定是slow的两倍。两者相遇的地方一定是环的起点。至于证明,直接参照引用贴。
时间O(n)
空间O(1)
1 /**
2 * @param {ListNode} head
3 * @return {ListNode}
4 */
5 var detectCycle = function(head) {
6 // corner case
7 if (head === null || head.next === null) {
8 return null;
9 }
10
11 // normal case
12 let slow = head;
13 let fast = head;
14 while (fast !== null && fast.next !== null) {
15 slow = slow.next;
16 fast = fast.next.next;
17 if (fast === slow) {
18 let slow2 = head;
19 while (slow !== slow2) {
20 slow = slow.next;
21 slow2 = slow2.next;
22 }
23 return slow;
24 }
25 }
26 return null;
27 };