题目
解题
没有思路的话,可以先看看官方的提示:
解题一:暴力解法
直接把节点(地址)存进 Set ,一旦发现相同地址重复出现,表明出现了循环,该地址便是环路的开头节点。
// javascript
var detectCycle = function(head) {
let listSet = new Set();
while (head !== null) {
if (!listSet.has(head)) {
listSet.add(head);
head = head.next;
}
else{
return head;
}
}
return null;
};
解题二:三指针法
书上的解答的第3部分没有写的很详细,为什么第三个指针和前两个指针相遇在环路的开头节点呢?LeetCode 官网解答进行了数学分析:
// javascript
var detectCycle = function(head) {
if (head === null) return null; // 可加,可不加
let slow = head, fast = head;
let hasLoop = false;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
hasLoop = true;
break;
}
}
if (!hasLoop) return null;
while (head !== slow) {
head = head.next;
slow = slow.next;
}
return head;
};