#include<iostream>
using namespace std;
//1.先判断是否有环,快慢指针,慢指针一次向后前进一格,快指针一次向后前进两格(注意判断是否为NULL)
//当快指针为NULL时,两指针仍为相遇则不存在环。
//2.判断环中包含元素的个数。
//以两指针相遇处为初始点,慢指针依次往后挪,并计数,当再次回到相遇点时,可求得包含元素个数n。
//3.找出环的入口。指针p1先向后移动n步,指针p2指向头结点,以相同速度移动两指针,当两指针再次相遇时的节点就是入口节点
struct ListNode
{
int value;
ListNode* next;
};
ListNode* MeetNode(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 (pSlow == pFast)
return pSlow;
pSlow = pSlow->next;
pFast = pFast->next;
if (pFast != NULL)
pFast = pFast->next;
}
return NULL;//找不到相遇点返回NULL
}
int CountNum(ListNode* pEnter)
{
int count = 1;
ListNode* p = pEnter->next;
while (p != pEnter)
{
count++;
p = p->next;
}
return count;
}
ListNode* EntryNode(ListNode * pHead, int count)
{
ListNode* p1 = pHead;
ListNode* p2 = pHead;
int i = 0;
while (i < count)
{
p2 = p2->next;
i++;
}
while (p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
链表中环的入口
最新推荐文章于 2015-10-11 09:45:12 发布