首页 > 其他分享 >判断单链表是否成环

判断单链表是否成环

时间:2023-02-22 14:24:53浏览次数:30  
标签:head 单链 return fast next 判断 null 成环 指针

快指针与慢指针

在环中,快指针走两步,慢指针走一步,快慢指针一定会相遇。需要注意的是,快慢指针相遇的地方,不一定是环的入口。

 public static boolean isCircleByTwoPoint(ListNode head){
     if (null == head || null == head.next){
         return false;
     }
     ListNode slow = head;
     ListNode fast = head;
     while (null != fast && null != fast.next){//注意这个条件,要防止空指针
         slow = slow.next;//slow 指针一次一步
         fast = fast.next.next;//fast指针一次两步
         if (slow == fast){
             return true;
         }
     }
     return false;
 }

哈希法 用这种方法可以找到环的入口

public static boolean isCircleByHash(ListNode head){
    if (null == head){
        return false;
    }

    Set<ListNode> set = new HashSet<>();//定义哈希集合
    while (null != head){
        if (set.contains(head)){//存在说明有环
            return true;
        }
        set.add(head);
        head = head.next;
    }
    return false;
}

标签:head,单链,return,fast,next,判断,null,成环,指针
From: https://www.cnblogs.com/jrjewljs/p/17144151.html

相关文章