0
点赞
收藏
分享

微信扫一扫

判断链表是否有环

ivy吖 2022-03-22 阅读 55

哈希存储

 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 条评论