1+ // Java program to detect loop in a linked list
2+ import java .util .*;
3+
4+ public class LinkedList {
5+
6+ static Node head ; // head of list
7+
8+ /* Linked list Node*/
9+ static class Node
10+ {
11+ int data ;
12+ Node next ;
13+ Node (int d ) {data = d ; next = null ; }
14+ }
15+
16+ /* Inserts a new Node at front of the list. */
17+ static public void push (int new_data )
18+ {
19+ /* 1 & 2: Allocate the Node &
20+ Put in the data*/
21+ Node new_node = new Node (new_data );
22+
23+ /* 3. Make next of new Node as head */
24+ new_node .next = head ;
25+
26+ /* 4. Move the head to point to new Node */
27+ head = new_node ;
28+ }
29+
30+ // Returns true if there is a loop in linked
31+ // list else returns false.
32+ static boolean detectLoop (Node h )
33+ {
34+ HashSet <Node > s = new HashSet <Node >();
35+ while (h != null )
36+ {
37+ // If we have already has this node
38+ // in hashmap it means their is a cycle
39+ // (Because you we encountering the
40+ // node second time).
41+ if (s .contains (h ))
42+ return true ;
43+
44+ // If we are seeing the node for
45+ // the first time, insert it in hash
46+ s .add (h );
47+
48+ h = h .next ;
49+ }
50+
51+ return false ;
52+ }
53+
54+ /* Driver program to test above function */
55+ public static void main (String [] args )
56+ {
57+ LinkedList llist = new LinkedList ();
58+
59+ llist .push (46 );
60+ llist .push (78 );
61+ llist .push (52 );
62+ llist .push (94 );
63+
64+ /*Create loop for testing */
65+ llist .head .next .next .next .next = llist .head ;
66+
67+ if (detectLoop (head ))
68+ System .out .println ("Loop found" );
69+ else
70+ System .out .println ("No Loop" );
71+
72+ }
73+ }
74+
0 commit comments