我必須找出一個鏈表循環,我已經找到了使用烏龜和野兔的解決方案如下在java中打破一個循環鏈表和尋找複雜
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;
}
}
,現在我的問題是如何能我檢測循環的開始,以及如何計算程序的複雜度,就像增加列表的大小一樣。指針遇到的點不會增加列表大小的比例。
下來選民,你可以告訴的原因 – ankit