給定一個鏈表,返回鏈表開始入環的第一個節點。 如果鏈表無環,則返回 null
爲了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
思路:
設定一個fast一次走兩步,slow一次走一步,當fast=slow時,此時證明單鏈表中有環,把slow輸出即可。
小思考:
本題給出的思路是fast是slow的二倍,那麼請思考一下,fast可不可以是slow的三倍?四倍?甚至更多倍呢?
答案肯定是可以的呢,只不過是運算時間的不同而已。但是事實證明,當fast是slow的二倍的時候走的是最少的,即運算時間是最短的。
代碼如下:
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast .next != null) {
fast = fast.next.next;
slow = slow.next;
if(slow == fast) {
break;
}
}
if(fast == null || fast.next == null) {
return null;
}
slow = head;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
}