O(1)解法 双指针
public boolean hasCycle(ListNode head) {
//快慢指针,如果满快指针先到达末尾,证明无环
if(head==null|| head.next==null){
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow!=fast){
if(fast==null || fast.next==null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
O(n)解法 哈希表
public boolean hasCycle2(ListNode head){
HashSet set = new HashSet();
//head指针不断移动,只要没有到表尾,就一直判断
while(head!=null){
// if(set.contains(head)){
// return true;
// }else{
// set.add(head);
// }
if(!set.contains(head)){
set.add(head);
}else{
return true;
}
head = head.next;
}
return false;
}