DEV Community

Debesh P.
Debesh P.

Posted on

141. Linked List Cycle | LeetCode | Top Interview 150 | Coding Questions

Problem Link

https://leetcode.com/problems/linked-list-cycle/


Detailed Step-by-Step Explanation

https://leetcode.com/problems/linked-list-cycle/solutions/7582225/beats-200-floyds-cycle-detection-tortois-1vng


leetcode 141


Solution

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

        ListNode slowPtr = head;
        ListNode fastPtr = head;

        while (slowPtr != null && fastPtr != null && fastPtr.next != null) {
            slowPtr = slowPtr.next;
            fastPtr = fastPtr.next.next;

            if (slowPtr == fastPtr) {
                return true;
            }
        }

        return false;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)