Data Structures & Algorithms View on GitHub โ†—

Linked List Cycle Detection

Java

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */

class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> seen = new HashSet<>();

        ListNode curr = head;
        while(curr != null){
            if(seen.contains(curr)){
                return true;
            }

            seen.add(curr);
            curr = curr.next;
        }

        return false;
    }
}

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow, fast = head, head

        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True 
        
        return False

Enjoyed this solution?

I write about software engineering, algorithms, and lessons learned. Check out more in the newsletter.

Browse the newsletter