Linked Lists: Detect a Cycle

  • + 4 comments

    Did something similar but just changed around the checks, unfortunatley I keep hitting a null pointer and I'm unsure why. Any thoughts?

    boolean hasCycle(Node head) {

    if(head==null){
        return false;
    }
    

    Node Fast = head.next; Node Slow = head;

    while(Fast.next != null || Fast != null){

       if(Fast == Slow){
           return true;
       }
       Fast = Fast.next.next;
       Slow = Slow.next;
    

    }

    return false;

    }

    P.S. Unfortunatley I can't seem to remember how to set which language I'm using on my comment