// public class ListNode { int val; ListNode next = null;
ListNode(int val) {
this.val = val;
}
} */ //快慢索引,具体见下图 public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode low = pHead;
ListNode fast = pHead;
if(pHead == null ) {//链表为空直接返回
return null;
}else{
low = low.next;//慢索引先走一步
if(low == null) return null;//为空返回
fast = fast.next;//快索引走一步
if(fast == null) return null;//为空返回
fast = fast.next;//快索引再走一步
if(fast == null) return null;//为空返回
//找到第一次相遇的节点
while(low != fast ){
low = low.next;//慢索引先走一步
if(low == null) return null;//为空返回
fast = fast.next;//快索引走一步
if(fast == null) return null;//为空返回
fast = fast.next;//快索引再走一步
if(fast == null) return null;//为空返回
}
}
//第一次相遇之后,快慢索引同速同步运动,慢索引返回头部重新开始运动
//快索引从相遇节点运动
//两个索引节点再次相遇时就是链表中环的入口
low = pHead;
while(low != fast){
low = low.next;
fast = fast.next;
}
return low;
}
} public class ListNode { int val; ListNode next = null;
ListNode(int val) {
this.val = val;
}
} */ public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode low = pHead;
ListNode fast = pHead;
if(pHead == null ) {
return null;
}else{
low = low.next;
if(low == null) return null;
fast = fast.next;
if(fast == null) return null;
fast = fast.next;
if(fast == null) return null;
while(low != fast ){
low = low.next;
if(low == null) return null;
fast = fast.next;
if(fast == null) return null;
fast = fast.next;
if(fast == null) return null;
}
}
low = pHead;
while(low != fast){
low = low.next;
fast = fast.next;
}
return low;
}
}