首页 > 其他 > 详细

判断一个链表是否有环

时间:2018-11-04 20:18:49      阅读:126      评论:0      收藏:0      [点我收藏+]

给定一个链表,判断链表中是否有环。

可以通过快慢指针,当快指针为NULL时就说明没有环,,当快指针追上慢指针,就说明有环。

public boolean hasCycle(ListNode head) {
    if (head == null || head.next == null) {
        return false;
    }
    ListNode slow = head;
    ListNode fast = head.next;
    while (slow != fast) {
        if (fast == null || fast.next == null) {
            return false;
        }
        slow = slow.next;
        fast = fast.next.next;
    }
    return true;
}

判断一个链表是否有环

原文:https://www.cnblogs.com/yihangZhou/p/9905382.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!