判断链表是否有环

ivy吖

关注

阅读 55

2022-03-22

哈希存储

 public boolean hasCycle(ListNode head) {
        
        HashSet<ListNode> map = new HashSet<ListNode>();
        ListNode temp = head;
        while(temp != null){
             if(map.contains(temp)){
                return true;
            }
            map.add(temp);
            temp = temp.next;
        }
        return false;
    }

在这里插入图片描述
快慢指针


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

在这里插入图片描述

精彩评论(0)

0 0 举报