def has_cycle(head):
slow=fast=head
while fast and fast.next:
slow=slow.next; fast=fast.next.next
if slow==fast: return True
return False
public boolean hasCycle(ListNode head){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next; fast=fast.next.next;
if(slow==fast) return true;
} return false;
}
Floyd's cycle. Python truthiness vs Java null checks.
def has_cycle(head):
slow=fast=head
while fast and fast.next:
slow=slow.next; fast=fast.next.next
if slow==fast: return True
return False
public boolean hasCycle(ListNode head){
ListNode slow=head,fast=head;
while(fast!=null&&fast.next!=null){
slow=slow.next; fast=fast.next.next;
if(slow==fast) return true;
} return false;
}
1. Slow and fast pointers 2. Meet: cycle