题解 | #判断链表中是否有环#
判断链表中是否有环
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
// 用一个数组存遍历过的节点,过下一个节点存在于数组中,则存在环
let myMap=new Map();
let p=head
while(p!==null){
if(myMap.has(p)){
return true
}else{
myMap.set(p)
}
p=p.next
}
return false
}
module.exports = {
hasCycle : hasCycle
};
或者另外一种方法。相对于第一个方法,空间复杂度低
function hasCycle( head ) {
// write code here
// 将遍历过的节点做标记,如果再次访问到有标记的节点,则存在环
while(head){
// 先判断是否做过标记,没有做过标记则做标记,并继续下一个节点
if(head.flag){
return true
}
head.flag=true;
head=head.next
}
}
