题解 | #判断链表中是否有环#
判断链表中是否有环
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
// 使用数组存放已经遍历过的节点的next,如果遍历时已经存过了,能在数组里面找到,就是有环
let arr = new Array();
while (head != null) {
if (arr.includes(head.next)) {
return true;
} else {
arr.push(head.next);
head = head.next;
}
}
}
module.exports = {
hasCycle: hasCycle,
};