主要思路:用两个指针,步长分别为1和2,遍历,相遇时即表示有环。
bool hasCircle(Node* head, Node* &encounter)
{
Node *fast = head, *low = head;
while(fast && fast->next)
{
fast = fast->next->next;
low = low->next;
if(fast == low)
{
encounter = fast;
return true;
}
}
// fast == NULL || fast->next == NULL
encounter = NULL;
return false;
}
找到环点
Node* findEntry(Node* head, Node* encounter)
{
Node *p1 = head, *p2 = encounter;
while(p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
}
return p1;
}
找到交点的思路是把其中链表一个链表首尾相连,如果有环,则回到第一个问题。