题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead) {
ListNode slow = yesNoStrike(pHead);
//如果无链表则返回为空
if(slow == null){
return null;
}
//快指针返回到头结点
ListNode fast = pHead;
//再次相遇即是环入口
while(fast != slow){
fast = fast.next;
slow = slow.next;
}
return slow;
}
public ListNode yesNoStrike(ListNode pHead) {
//如果无链表则返回为空
if(pHead == null){
return null;
}
//快慢指针
ListNode fast = pHead;
ListNode slow = pHead;
//如果没环快指针会先到链表尾
while(fast != null && fast.next != null){
//快指针移动两步
fast = fast.next.next;
//慢指针移动一步
slow = slow.next;
//快慢指针碰撞则相遇
if(fast == slow){
return slow;
}
}
return null;
}
}

