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