public class Solution {
public static void main(String[] args) {
ListNode node1 = new ListNode(3, new ListNode(2, new ListNode(0, new ListNode(4))));
boolean res = hasCycle(node1);
System.out.println("输出: " + res);
}
public static boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
public static boolean hasCycle2(ListNode head) {
int count = 0;
while (head != null) {
if (count > 10000) {
return true;
}
head = head.next;
count++;
}
return false;
}
public static boolean hasCycle1(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}