次のように、タートルとウサギのソリューションを使用して見つけたリンクリストのループを見つける必要があります
boolean hasLoop(Node first) {
if(first == null) // list does not exist..so no loop either.
return false;
Node slow, fast; // create two references.
slow = fast = first; // make both refer to the start of the list.
while(true) {
slow = slow.next; // 1 hop.
if(fast.next != null)
fast = fast.next.next; // 2 hops.
else
return false; // next node null => no loop.
if(slow == null || fast == null) // if either hits null..no loop.
return false;
if(slow == fast) // if the two ever meet...we must have a loop.
return true;
}
}
そして今、私の問題は、ループの開始を検出する方法と、リストのサイズを大きくしたかのようにプログラムの複雑さを計算する方法です。ポインターが出会うポイントは、リストのサイズの割合で増加しません。