给定单链表,如果有环的话请返回从头结点进入环的第一个节点。
Node* firstnode(List plist)
{
assert(plist != NULL);
if (plist == NULL||plist->next==NULL)
{
return NULL;
}
Node* fast=plist->next->next;
Node* lower=plist->next;
Node* p;
Node* q;
while (fast != NULL && fast->next != NULL)
{
if (fast == lower)
{
break;
}
lower = lower->next;
fast = fast->next->next;
}
if (fast == NULL||fast->next==NULL)
{
return NULL;
}
p = plist;
q = fast;
while (p != q||p==NULL||q==NULL)
{
p = p->next;
q = q->next;
}
if (p == NULL || q == NULL)
{
return NULL;
}
return p;
}
求链表入环的第一个交点
最新推荐文章于 2024-06-24 17:49:50 发布