Leetcode 142 : Linked List Cycle ii
Solution to Return begining node of a Linked List Cycle Problem. This resource contains an excellent explanation of why the below approach works.
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode sp = head;
ListNode fp = head;
boolean hasCycle = false;
while(fp != null && fp.next != null) {
fp = fp.next.next;
sp = sp.next;
if(fp == sp) {
hasCycle = true;
break;
}
}
if(!hasCycle) {
return null;
}
sp = head;
while(fp != sp) {
sp = sp.next;
fp = fp.next;
}
return sp;
}
}