哈希存储
public boolean hasCycle(ListNode head) {
HashSet<ListNode> map = new HashSet<ListNode>();
ListNode temp = head;
while(temp != null){
if(map.contains(temp)){
return true;
}
map.add(temp);
temp = temp.next;
}
return false;
}
快慢指针
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next!= null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}