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;
}
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)