public class E23FindEntryFromLoop {
private class ListNode{
int value;
ListNode nextNode;
}
public static ListNode entryNodeOfLoop(ListNode head){
if (head == null)
return null;
ListNode loopNode = meetingNode(head);
if (loopNode == null)
return null;
int count = 1;
ListNode node = loopNode;
while(node.nextNode != loopNode){
loopNode = loopNode.nextNode;
count ++;
}
ListNode ahead = head;
ListNode behind = head;
for (int i = 0; i < count; i ++)
ahead = ahead.nextNode;
while(ahead != behind){
ahead = ahead.nextNode;
behind = behind.nextNode;
}
return behind;
}
private static ListNode meetingNode(ListNode head){
ListNode fast = head;
ListNode slow = head;
fast = fast.nextNode;
while(slow != null && fast != null){
if (slow == fast)
return slow;
slow = slow.nextNode;
fast = fast.nextNode;
if (fast != null)
fast = fast.nextNode;
}
return null;
}
}