Skip to content

Commit 162baf5

Browse files
Added Tortoise and Hare algorithm with unit tests
1 parent 6e1664a commit 162baf5

File tree

4 files changed

+30
-29
lines changed

4 files changed

+30
-29
lines changed

src/main/java/com/thealgorithms/LinkedList/DoublyLinkedLIst.java

Whitespace-only changes.

src/main/java/com/thealgorithms/LinkedList/SingleLinkedList.java

Lines changed: 0 additions & 29 deletions
This file was deleted.
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package com.thealgorithms.LinkedList;
2+
3+
/**
4+
* Detects a cycle in a singly linked list using Tortoise and Hare algorithm
5+
*/
6+
public class TortoiseAndHare {
7+
8+
static class ListNode {
9+
int val;
10+
ListNode next;
11+
12+
ListNode(int x) {
13+
this.val = x;
14+
next = null;
15+
}
16+
}
17+
18+
public boolean hasCycle(ListNode head) {
19+
ListNode slow = head;
20+
ListNode fast = head;
21+
22+
while (fast != null && fast.next != null) {
23+
slow = slow.next;
24+
fast = fast.next.next;
25+
26+
if (slow == fast) return true;
27+
}
28+
return false;
29+
}
30+
}

src/main/java/com/thealgorithms/LinkedList/Tortoise_and_harealgo.java

Whitespace-only changes.

0 commit comments

Comments
 (0)