题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null
/*
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 pHead;
}
ListNode fast = pHead;
ListNode slow = pHead;
boolean isExist = false;
while (slow.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
isExist = true;
break;
}
}
if (isExist) {
slow = pHead;
while (slow != null && fast != null) {
if (slow == fast) {
return slow;
}
slow = slow.next;
fast = fast.next;
}
}
return null;
}
}