原题链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/
在141. 环形链表,JavaScript HashMap,详细注释的基础上优化而成。
/**
* @param {ListNode} head
* @return {ListNode}
*/
var detectCycle = function (head) {
// 如果没有节点或只有一个非环的节点,则直接返回null
if (!head || !head.next) {
return null;
}
// 如果只有一个节点,且其自身形成一个环,则直接返回
if (head.next === head) {
return head;
}
// 使用Set判断是否有环存在
let set = new Set();
// 缓存头节点,用node进行遍历
let node = head;
// 遍历链表,如果节点为空则退出
while (node) {
// 如果已存储过节点的指向,表示已经找到环,则返回当前节点指向的元素
// 但如果碰到2个节点互相指向时,会把head节点的指向误当做结果返回,应迪需要排除头节点的判断
if (node !== head && set.has(node.next)) {
return node.next;
}
// 将当前指向添加到Set以作判断
set.add(node.next);
// 移动节点,继续遍历
node = node.next;
}
return null;
};