Что не так с моей реализацией? < /P>
Вот мой код: < /p>
Код: Выделить всё
class ListNode {
int val;
ListNode next;
ListNode(int val) {
this.val = val;
this.next = null;
}
}
public class LinkedListCycleDetection {
public static 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;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = head.next;
System.out.println(hasCycle(head));
}
}
Geeksforgeeks - Обнаружение цикла в связанном списке
Подробнее здесь: https://stackoverflow.com/questions/794 ... st-in-java