题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return bool布尔型
*/
function hasCycle( head ) {
// write code here
const set = new Set()
let cur = head
while (cur) {
// 如果当前访问的节点,哈希表中已经有该节点,说明有环
if (set.has(cur))
return true
// 哈希表存入已经访问过的节点
set.add(cur)
cur = cur.next
}
return false
}
module.exports = {
hasCycle : hasCycle
};
查看12道真题和解析