题目

代码
法一:快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
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;
}
}
法二:hashset
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> listSet = new HashSet<>();
ListNode p = head;
while(true) {
if(p == null) return false;
if(listSet.contains(p)) return true;
listSet.add(p);
p = p.next;
}
}
}
结果



166

被折叠的 条评论
为什么被折叠?



