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

Commit c0fca52

Browse files
committed
LinkedListDetectCycle Alogrithm
1 parent 8aefdfd commit c0fca52

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed
+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
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+
}

src/main/java/Node.java

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

0 commit comments

Comments
 (0)