Advertisement
Detect Loop in linked list
JavaView on GFG
Detect Loop in linked list.java
Java
class Node {
int data;
Node next;
Node(int d) {
data = d;
next = null;
}
}
class Solution {
// Function to check if the linked list has a loop.
public static boolean detectLoop(Node head) {
Node slow = head;
Node fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast)
return true;
}
return false;
}
}Advertisement
Was this solution helpful?