设置快慢指针,如果链表是环形的,一快一慢的两个指针在环中一定相遇。
public boolean hasCycle(ListNode head) {
ListNode slow=head;
ListNode fast=head;
while(fast!=null&&fast.next!=null){
fast=fast.next.next;
slow=slow.next;
if(fast==slow){
return true;
}
}
return false;
}
public boolean hasCycle(ListNode head){
ListNode fast=head;
ListNode slow=head;
while(fast!=null){
fast=fast.next;
if(fast!=null){
fast=fast.next;
}
if(fast==slow){
return true;
}
slow=slow.next;
}
return false;
}