Detecting a cycle in a linked list using Java I'm solving HackerRank "Linked Lists: Detect a Cycle" challenge.


  A linked list is said to contain a cycle if any node is visited more
  than once while traversing the list.
  
  Complete the function provided in the editor below. It has one
  parameter: a pointer to a Node object named head that points to the head
  of a linked list. Your function must return a boolean denoting whether
  or not there is a cycle in the list. If there is a cycle, return true;
  otherwise, return false.
  
  Note: If the list is empty, head will be null.


/*
Detect a cycle in a linked list. Note that the head pointer may be 'null' if the list is empty.

A Node is defined as: 
    class Node {
        int data;
        Node next;
    }
*/

boolean hasCycle(Node head) {
    HashSet&lt;Node&gt; seen = new HashSet&lt;Node&gt;();

    Node current = head;
    while (current != null &amp;&amp; current.next != null) {
        if (seen.contains(current)) {
            return true;
        }

        seen.add(current);
        current = current.next;
    }

    return false;
}


As a beginner Java developer, what can be improved here?
The method should be public.

Testing for the current.next != null condition is unnecessary. Also, consider writing the loop as a for loop for clarity:

for (Node current = head; current != null; current = current.next) {
    …
}


You don't need to call seen.contains(), because seen.add() will return false if the item you are adding is already in the set.