版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kaikai_sk/article/details/88099942
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
/**
求链表环入口:
1. 确定有无环
2. 确定环的长度
3. 快慢指针确定入口
**/
public class Solution {
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead == null)
return null;
else if(pHead.next == null)
return null;
ListNode slow = pHead;
ListNode fast = pHead;
ListNode common = null;
while(slow!=null && fast!=null)
{
slow = slow.next;
fast = fast.next.next;
if(slow == fast)
{
common = slow;
break;
}
}
if(common == null)
return null;
int len =1;
ListNode start = common.next;
while(start!=common)
{
start = start.next;
len++;
}
slow = pHead;
fast = pHead;
for(int i=0;i<len;i++)
{
fast = fast.next;
}
while(slow != fast)
{
slow = slow.next;
fast = fast.next;
}
return slow;
}
}