class LinkedNode{
int val;
LinkedNode next;
}
public class T56 {
//找到环内任意点
private LinkedNode meetNode(LinkedNode head){
if(head==null)
return null;
LinkedNode slow=head.next;
if(slow==null)
return null;
LinkedNode fast=slow.next;
while(fast!=null && slow!=null){
if(fast==slow)
return fast;
slow=slow.next;
fast=fast.next;
if(fast!=null)
fast=fast.next;
}
return null;
}
//得出环中的节点数,找到环的入口点
LinkedNode entryNodeOfLoop(LinkedNode head){
LinkedNode meetNode=meetNode(head);
if(meetNode==null)
return null;
int nodesInLoop=1;
LinkedNode p=meetNode;
//得到环中节点的个数
while(p.next!=meetNode){
p=p.next;
++nodesInLoop;
}
//让p指向头节点
p=head;
//p先走nodesInLoop步
for(int i=0;i<nodesInLoop;++i)
p=p.next;
//p2指向头节点
LinkedNode p2=head;
//当p1&p2 相遇时,这时候就是入口的位子
while(p!=p2){
p=p.next;
p2=p2.next;
}
return p;
}