判断单链表是否成环

快指针与慢指针

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

 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;
}
posted @ 2023-02-22 14:10  jrjewljs  阅读(27)  评论(0编辑  收藏  举报