Failed at 12th test case. why ?


  • 0
    A

    public ListNode detectCycle(ListNode head) {
    if(head==null || head.next==null)
    return null;
    if(head.next==head)
    return head;

        ListNode slow=head;
        ListNode fast=head.next.next;
    
        while (slow!=fast && fast!=null && fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
    
        if(slow==fast)
            return slow;
    
        return null;
    }

  • 0
    X

    The approach is not correct. if slow==fast, that only means there is a cycle, but the meeting node might not be the head of cycle


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.