Skip to content

Commit 4348a8e

Browse files
Merge pull request #243 from makajeez/master
Floyd_Cycle_Loop_Detection.Java
2 parents 4a13638 + 6de6151 commit 4348a8e

File tree

1 file changed

+62
-0
lines changed

1 file changed

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

0 commit comments

Comments
 (0)