DEV Community

Giuseppe
Giuseppe

Posted on

LeetCode #141. Linked List Cycle

Time Complexity: O(n)

Space Complexity: O(1)

public class Solution {
    public boolean hasCycle(ListNode head) {

         if (head == null || head.next == null) {
            return false;
        }

        // Initialize two pointers
        ListNode slow = head;
        ListNode fast = head;

        // Move pointers until they meet or fast reaches end
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;

            // If pointers meet, there's a cycle
            if (slow == fast) {
                return true;
            }
        }

        // Fast pointer reached end, no cycle
        return false;

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)