利用hash表来存放地址 得到是否重复
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null)return false;
HashSet hs = new HashSet<ListNode>();
while(head!=null){
if(hs.contains(head))
return true;
else {
hs.add(head);
}
head = head.next;
}
return false;
}
}可以用快慢指针 一个走两步 一个走一步 如果存在循环说明一个迟早回追到另外一个
public boolean hasCycle(ListNode head) {
if(head==null)return false;
ListNode end = head.next;
while(head!=null&&end!=null&&end.next!=null){
if(end==head)return true;
end = end.next.next;
head = head.next;
}
return false;
}
}
京公网安备 11010502036488号