Skip to content
This repository was archived by the owner on Aug 13, 2024. It is now read-only.

Commit edefe98

Browse files
committed
LinkedListDetectCycle Alogrithm
1 parent 8aefdfd commit edefe98

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

Diff for: src/main/java/algorithms/LinkedListsDetectCycle.java

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package algorithms;
2+
3+
import java.util.ArrayList;
4+
import java.util.List;
5+
6+
public class LinkedListsDetectCycle {
7+
8+
public boolean solve(Node head) {
9+
List<String> visited = new ArrayList<String>();
10+
if (head == null) {
11+
return false;
12+
} else {
13+
visited.add("@" + System.identityHashCode(head));
14+
Node next = head.next;
15+
while (next != null) {
16+
int hash = System.identityHashCode(next);
17+
if (visited.contains("@" + hash)) {
18+
return true;
19+
} else {
20+
visited.add("@" + hash);
21+
}
22+
next = next.next;
23+
}
24+
return false;
25+
}
26+
}
27+
}

Diff for: src/main/java/algorithms/Node.java

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package algorithms;
2+
3+
public class Node {
4+
int data;
5+
public Node next;
6+
7+
public Node(int data, Node next) {
8+
this.data = data;
9+
this.next = next;
10+
}
11+
}

Diff for: test/main/java/LinkedListsDetectCycleTest.java

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import org.junit.Assert;
2+
import org.junit.Test;
3+
4+
import algorithms.LinkedListsDetectCycle;
5+
import algorithms.Node;
6+
7+
/**
8+
* @author medany
9+
*/
10+
11+
public class LinkedListsDetectCycleTest {
12+
13+
@Test
14+
public void Test_True() {
15+
16+
LinkedListsDetectCycle alg = new LinkedListsDetectCycle();
17+
18+
Node head = new Node(1, new Node(2, new Node(3, null)));
19+
head.next.next.next = head.next;
20+
21+
boolean actual = alg.solve(head), expected = true;
22+
23+
Assert.assertEquals(expected, actual);
24+
25+
}
26+
27+
@Test
28+
public void Test_False() {
29+
30+
LinkedListsDetectCycle alg = new LinkedListsDetectCycle();
31+
32+
Node head = new Node(1, null);
33+
34+
boolean actual = alg.solve(head), expected = false;
35+
36+
Assert.assertEquals(expected, actual);
37+
38+
}
39+
40+
}

0 commit comments

Comments
 (0)