/**
* Definition for singly-linked list.
* public class ListNode {
* public int val;
* public ListNode next;
* public ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public bool HasCycle(ListNode head) {
var slow = head;
var fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) return true;
}
return false;
}
}Once both pointers are inside the cycle, fast gains exactly one node on slow per step, so the gap between them shrinks by 1 each step (…, 2, 1, 0). It can’t jump over 0, so they must land on the same node. If there’s no cycle, fast just hits null first.