题目:
一个链表中包含环,请找出该链表的环的入口结点。
分析:
分两步:
1.利用两个指针知道链表的环中的结点数。
2.利用两个指针找到入口结点。
class Solution
{
public:
ListNode* EntryNodeOfLoop( ListNode* pHead )
{
ListNode* meetingNode = MeetingNode( pHead );
if ( meetingNode == NULL )
return NULL;
int nodesInLoop = 1;
ListNode* pNode1 = meetingNode;
while ( pNode1->next != meetingNode )
{
pNode1 = pNode1->next;
++nodesInLoop;
}
pNode1 = pHead;
for ( int i = 0; i < nodesInLoop; ++i )
pNode1 = pNode1->next;
ListNode* pNode2 = pHead;
while ( pNode1 != pNode2 )
{
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
return pNode1;
}
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;
}
};