“`” 【参考答案】

答:用两个指针来遍历这个单向链表,第一个指针p1,每次走一步;第二个指针p2,每次走两
步;当p2 指针追上p1的时候,就表明链表当中有环路了。

<pre><code>int testLinkRing(Link *head)
{
Link *t1=head,*t2=head;
while( t1->next && t2->next)
{
t1 = t1->next;
if (NULL == (t2 = t2->next->next))
return 0; // 无环
if (t1 == t2)
return 1;
}
return 0;
}
</code></pre>

<pre><code> "“`

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.