栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java如何检测链表中的循环?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java如何检测链表中的循环?

想法是要有两个引用列表,并以不同的速度移动它们。一个向前移动一个

1
节点,另一个向前移动
2

  • 如果链表有循环,它们肯定会碰面。
  • 否则,这两个引用(或其引用
    next
    )中的任何一个都将变为
    null

    实现该算法的Java函数:
boolean hasLoop(Node first) {    if(first == null) // list does not exist..so no loop either        return false;    Node slow, fast; // create two references.    slow = fast = first; // make both refer to the start of the list    while(true) {        slow = slow.next;          // 1 hop        if(fast.next != null) fast = fast.next.next; // 2 hops        else return false;          // next node null => no loop        if(slow == null || fast == null) // if either hits null..no loop return false;        if(slow == fast) // if the two ever meet...we must have a loop return true;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395133.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号