Skip to content

Commit f53a458

Browse files
authored
Add Floyd_Cycle_Loop_Detection in Java
1 parent 9ac05d1 commit f53a458

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// A linked list node
2+
class Node
3+
{
4+
int data;
5+
Node next;
6+
7+
Node(int data, Node next) {
8+
this.data = data;
9+
this.next = next;
10+
}
11+
};
12+
13+
class Main
14+
{
15+
// Function to detect Cycle in a linked list using Hashing
16+
public static boolean detectCycle(Node head)
17+
{
18+
Node curr = head;
19+
Set<Node> set = new HashSet();
20+
21+
// traverse the list
22+
while (curr != null)
23+
{
24+
// return false if we already have seen this node before
25+
if (set.contains(curr)) {
26+
return true;
27+
}
28+
29+
// insert current node into the set
30+
set.add(curr);
31+
32+
// move to the next node
33+
curr = curr.next;
34+
}
35+
36+
// we reach here if list does not contain any cycle
37+
return false;
38+
}
39+
40+
// Detect Cycle in a linked list
41+
public static void main(String[] args)
42+
{
43+
// input keys
44+
int[] keys = {1, 2, 3, 4, 5};
45+
46+
Node head = null;
47+
for (int i = keys.length - 1; i >= 0; i--)
48+
head = new Node(keys[i], head);
49+
50+
// insert cycle
51+
head.next.next.next.next.next = head.next.next;
52+
53+
if (detectCycle(head)) {
54+
System.out.println("Cycle Found");
55+
} else {
56+
System.out.println("No Cycle Found");
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)