题解 | #链表中环的入口结点#
链表中环的入口结点
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) { if(pHead == null){ return null; } ListNode p1 = pHead; ListNode p2 = pHead; while(p1 != null && p2 != null){ p1 = p1.next; if(p2.next != null){ p2 = p2.next.next; } //相遇说明存在环 if(p1 == p2){ //cur节点从头出发,Cur走一步,p1走一步,两者相遇处即为环的入口 ListNode cur = pHead; while(cur != p1){ cur = cur.next; p1 = p1.next; } return cur; } } //不存在环, 返回null return null; } }