/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode p = head;
Set<ListNode> set = new HashSet<>();
while (p != null) {
if (set.contains(p)) {
return true;
}
set.add(p);
p = p.next;
}
return false;
}
}
class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head, fast = head.next;
while (true) {
if (fast == null) {
return false;
}
if (fast == slow) {
return true;
}
fast = fast.next;
if (fast == null) {
return false;
}
if (fast == slow) {
return false;
}
fast = fast.next;
slow = slow.next;
}
}
}