Cycle Detection

Sort by

recency

|

33 Discussions

|

  • + 0 comments

    again this question is bugged... the example of the cycle:

    1 -> 2 -> 3 -> 1 -> NULL
    

    1 can't point to both 1 and NULL!

    At least this time the ro class compiles!

    static bool hasCycle(SinglyLinkedListNode head) {
        var d = new HashSet<SinglyLinkedListNode>();
        while(head is not null){
            if(d.Contains(head)) return true;
            d.Add(head);
            head = head.next;
        }
        return false;
    }
    
  • + 0 comments

    Only python works for me...

    Floyd cycle approach

    def has_cycle(head):
        slow = head
        fast = head
        
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
            
            if (slow == fast):
                return 1
        
        return 0
    
  • + 1 comment

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

  • + 0 comments
    def has_cycle(head):
        visited = set()
        while n:=head.next:
            if n in visited:
                return 1
            else:
                visited.add(n)
                head = n
        return 0
    
  • + 0 comments

    C++

    bool has_cycle(SinglyLinkedListNode* head) {
        unordered_set<SinglyLinkedListNode*> address; // a set of SLL num_set
        
        // for every node until the end of the SLL    
        while (head){        
            if (address.find(head) != address.end()) // if found the head in address
                return 1; // return 1 and terminate
            else 
                address.insert(head); // if did not find the head in address, then insert head as another element in address
                
            head = head->next; // move to the next node in the SLL
        }
        return 0; // if we got here then return zero
    }