牛客NC4 判断链表中是否有环(快慢指针)

题目
在这里插入图片描述
快慢指针判断是否相遇

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

猜你喜欢

转载自blog.csdn.net/qq_43434328/article/details/114901724
今日推荐