题解 | #判断链表中是否有环#

判断链表中是否有环

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
    }
    
}

全部评论

相关推荐

06-20 17:42
东华大学 Java
凉风落木楚山秋:要是在2015,你这简历还可以月入十万,可惜现在是2025,已经跟不上版本了
我的简历长这样
点赞 评论 收藏
分享
asdasdasda...:19岁,不容易啊可能升个本会好点,现在学历歧视太严重了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务