Cycle Detection

Sort by

recency

|

32 Discussions

|

  • + 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
    }
    
  • + 0 comments

    C# Solution:

    static bool hasCycle(SinglyLinkedListNode head) {
    
            List<SinglyLinkedListNode> list = new List<SinglyLinkedListNode>();
            while(head!=null) 
            {
                if (list.Contains(head)) 
                {
                    return true;
                } 
                else 
                {
                    list.Add(head);
                    head = head.next;
                }
            }
            return false;
        }