复习-JZ55 链表中环的入口结点
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&&tqId=11208&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
/*
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 || pHead.next == null)
return null;
ListNode p1 = pHead;
ListNode p2 = pHead;
while(p2 != null && p1.next != null){
p1 = p1.next;
p2 = p2.next.next;
if(p1==p2){
p2 = pHead;
while(p1!=p2){
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
}
return null;
}
}