ListNode *hasCycle(ListNode *head) { ListNode *slow=head; ListNode *fast=head; while(fast!=NULL && fast->next!=NULL) { slow=slow->next; fast=fast->next->next; if(fast==slow) return slow; } return NULL; } ListNode *detectCycle(ListNode *head) { ListNode *t1=hasCycle(head); if(t1==NULL)return NULL; ListNode *t=head; while(t!=t1) { t=t->next; t1=t1->next; } return t; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter