← Linked Lists

Linked List Cycle

Easy
Python
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
Java
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;
}

Key Insight

Floyd's cycle. Python truthiness vs Java null checks.

Python → Java Differences

  • while fast and fast.next vs !=null
  • True/False vs true/false
  • Floyd's identical
Python
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
Java
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;
}

Algorithm Steps

1. Slow and fast pointers
2. Meet: cycle