public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
//定义快慢指针,第一次相遇的时候走的差距就是环的大小,然后将f指针移到头节点再次进行遍历再次相遇的位置就是入口节点
if(pHead==null){
return null;
}
ListNode s = hasCycle(pHead);
ListNode f = pHead;
if(s==null){
return null;//无环
}
while(f!=s){
f = f.next;
s = s.next;
}
return s;
}
public ListNode hasCycle(ListNode head){
ListNode f = head;
ListNode s = head;
while(f!=null && f.next!=null){
f = f.next.next;
s = s.next;
if(s==f){
return s;
}
}
return null;
}
}



京公网安备 11010502036488号