This is my solution to challenge “Linked Lists: Detect a Cycle” on HackerRank. Click here to see the challenge.
/* 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) { if(head == null || head.next == null) { return false; } HashSet<Node> visited = new HashSet<Node>(); Node currentNode = head.next; while(currentNode != null) { if(visited.contains(currentNode)){ return true; }else{ visited.add(currentNode); } currentNode = currentNode.next; } return false; }
There is another solution which is better in terms of space complexity in which you can have two pointers one small pointer and one fast pointer. The small pointer jumps by one element in each iteration while the fast pointer jumps by two or more. If at any point fast pointer and small pointer point to same element then there is a cycle in the linked list. In this way, you don’t need to define an additional hashset.