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 namedhead
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<Node> seen = new HashSet<Node>(); Node current = head; while (current != null && 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?