//判断链表是否有环
int HasCircle(Node* pHead)
{
Node* low=pHead;
Node* fast=pHead;
while(fast != NULL && fast->next != NULL)
{
low=low->next;
fast=fast->next->next;
if(low==fast)
return 1;
}
return 0;
}
时间复杂度:O(1)
//求环中快慢指针相遇节点
Node* HasCircle(Node* pHead)
{
Node* low=pHead;
Node* fast=pHead;
if(pHead==NULL)
return NULL;
while(fast != NULL && fast->next != NULL)
{
low=low->next;
fast=fast->next->next;
if(low==fast)
return low;
}
return NULL;
}
//求环长度
int GetCircleLen(Node* pMeetNode)
{
Node* Node = pMeetNode->next;
int lenght = 1;
while(Node != pMeetNode )
{
lenght++;
Node = Node->next;
}
return lenght;
}
时间复杂度:O(1)
//求环的入口
Node* GetEnterNode(Node* pHead, Node* pMeetNode)
{
Node* start = pHead;
if(pHead == NULL)
return NULL;
while(start != pMeetNode)
{
start = start->next;
pMeetNode = pMeetNode->next;
}
return start;
}
时间复杂度:O(1)
本文详细介绍了如何使用快慢指针法判断链表是否存在环,找到环中的相遇节点,并进一步求解环的长度及环的入口节点。通过几个简单而有效的函数实现,展示了算法的时间复杂度均为O(1)。

被折叠的 条评论
为什么被折叠?



