O(N) C# solution - easy to understand , using HashSet


  • 0
    K
    public ListNode DetectCycle(ListNode head) {
        
        if(head == null) return head;
        
        HashSet<ListNode> set = new HashSet<ListNode>();
        
        while(head != null){
            
            if(set.Contains(head.next)){
                return head.next;
            }
            
            else
                set.Add(head);
            
            head = head.next;
            
        }
        
        return null;
    }

Log in to reply
 

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