题目描述
一个链表中包含环,请找出该链表的环的入口结点。
解题思路
可以用两个指针来解决这个问题。先定义两个指针 P1 和 P2 指向链表的头结点。如果链表中环有 n 个结点,指针 P1 在链表上向前移动 n 步,然后两个指针以相同的速度向前移动。当第二个指针指向环的入口结点时,第一个指针已经围绕着环走了一圈又回到了入口结点。
public ListNode EntryNodeOfLoop(ListNode pHead)
{
if(pHead==null)
return null;
ListNode node=MeetingNode(pHead);
if(node==null)
return null;
ListNode temp=node.next;
int n=1;
while(temp!=node){
n++;
temp=temp.next;
}
ListNode p=pHead;
ListNode q=pHead;
for(int i=0;i<n;i++){
q=q.next;
}
while(p!=q){
p=p.next;
q=q.next;
}
return p;
}
private ListNode MeetingNode(ListNode pHead){
if(pHead==null)
return null;
ListNode pSlow=pHead.next;
if(pSlow==null)
return null;
ListNode pFast=pSlow.next;
while(pFast!=null&&pSlow!=null){
if(pFast==pSlow)
return pFast;
pSlow=pSlow.next;
pFast=pFast.next;
if(pFast!=null)
pFast=pFast.next;
}
return null;
}