题目描述
给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null。
代码
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
ListNode fast = pHead;
ListNode slow = pHead;
while(fast != null && fast.next != null)
{
fast = fast.next.next;
slow = slow.next;
if(fast == slow)
{
ListNode p = pHead;
ListNode q = slow;
while(p != q)
{
p = p.next;
q = q.next;
}
return q;
}
}
return null;
}
}