Skip to content

Commit 60cf867

Browse files
solves linked cycle list
1 parent 5ef6197 commit 60cf867

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

src/LinkedListCycle.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
public class LinkedListCycle {
5+
static class ListNode {
6+
int val;
7+
ListNode next;
8+
ListNode(int x) {
9+
val = x;
10+
next = null;
11+
}
12+
}
13+
14+
public boolean hasCycle(ListNode head) {
15+
Set<ListNode> nodes = new HashSet<>();
16+
while (head != null) {
17+
if (nodes.contains(head)) {
18+
return true;
19+
} else {
20+
nodes.add(head);
21+
}
22+
head = head.next;
23+
}
24+
return false;
25+
}
26+
}

0 commit comments

Comments
 (0)