function detectAndRemoveCycle(head){
let slow = head, fast = head;
let hasCycle = false;
while(fast && fast.next){
slow = slow.next;
fast = fast.next.next;
if(slow === fast){ hasCycle = true; break; }
}
if(!hasCycle) return head;
slow = head;
while(slow.next !== fast.next){ slow = slow.next; fast = fast.next; }
fast.next = null;
return head;
}
Explanation: Detect cycle with slow/fast pointers. Move slow to head, keep fast at meeting point. Move both one step until next matches to remove cycle.
β± O(n) | πΎ O(1)