假设存在环, 环前共L个节点, 环中共C个节点.
设一个慢指针起始位置为a, 速度为1, 快指针起始位置为b, 速度为2.
t时间后, 二者相遇, 可列方程:
(a+t-L)mod C == (b+2*t-L)mod C
即t=a-b(mod C), 该模线性方程必定有解.
所以无论a, b的起始位置如何, 二者总是会相遇的.
Struct Node
{
int data;
Node* Next;
};
void check_chain_circle(Node* temp)
{
Node* head1=temp;
Node* head2=temp;
while(head1->next!=head2->next->next)
{
head1=head1->next;
head2=head2->next->next;
if(head1==NULL||head2==NULL)
{
printf("No circle!/n");
return;
}
}
printf("Yes, the chain has circle!/n");
return;
}
2011-04-27 16:04:29