Here is the solution:
function detect_cycle(head)
slow := head
fast := head
while fast and fast.next
slow := slow.next
fast := fast.next.next
if slow = fast then
ptr := head
while ptr != slow
ptr := ptr.next
slow := slow.next
return ptr
return null
Time: where is the number of nodes. Space: since you only use two pointers. No visited set needed. The algorithm is simple but powerful.