https://leetcode-cn.com/problems/linked-list-cycle/submissions/
1、使用集合
public class Solution {
public static boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while (head != null) {
//如果Set集合中不包含要添加的对象,则添加对象并返回true;否则返回false
if (!seen.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}
2、使用快慢指针
public class Solution {
public static boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode slow = head;
ListNode fast = head.next;
while(fast != slow) {
if(fast==null || fast.next==null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}