public class 链表中的环入口节点
{
// pHead为第一个节点
private ListNode entryNodeOfCycle(ListNode pHead)
{
ListNode meetNode = meetNode(pHead);
// 如果没有环
if (meetNode == null)
{
return null;
}
// 计算环的长度
int lengthOfCycle = 1;
ListNode curNode = meetNode;
while (curNode.next != meetNode)
{
lengthOfCycle++;
curNode = curNode.next;
}
/*
* 找出入口节点 利用快慢指针,前者先行lengthOfCycle个节点,然后两者同时前进当fast==low时返回即为入口节点
*
*/
ListNode fast = pHead, low = pHead;
for (int i = 0; i < lengthOfCycle; i++)
{
fast = fast.next;
}
while (fast != low)
{
fast = fast.next;
low = low.next;
}
return fast;
}
/*
* 第一步利用快慢指针找到它们相遇的节点 第二步计算出环内节点个数 第三步找到入口
*/
private ListNode meetNode(ListNode pHead)
{
// 特殊值考虑
if (pHead == null || pHead.next == null)
{
return null;
}
ListNode fast = pHead;
ListNode low = pHead;
while (fast.next != null && fast.next.next != null)
{
fast = fast.next.next;
low = low.next;
if (fast == low)
{
return fast;
}
}
return null;
}
}