Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Java
Submodule Java added at c0ca70
30 changes: 30 additions & 0 deletions src/main/java/com/thealgorithms/LinkedList/TortoiseAndHare.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.thealgorithms.LinkedList;

/**
* Detects a cycle in a singly linked list using Tortoise and Hare algorithm
*/
public class TortoiseAndHare {

static class ListNode {
int val;
ListNode next;

ListNode(int x) {
this.val = x;
next = null;
}
}

public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;

while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;

if (slow == fast) return true;
}
return false;
}
}
Loading