題目地址:
https://www.lintcode.com/problem/linked-list-cycle-ii/description
給定一個鏈表,判斷其是否有環。如果無環,則返回null,否則返回環的入口。參考https://blog.csdn.net/qq_46105170/article/details/104015181。代碼如下:
public class Solution {
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins. if there is no cycle, return null
*/
public ListNode detectCycle(ListNode head) {
// write your code here
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
// slow每次走一步,fast每次走兩步
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
break;
}
}
// 如果fast走到了表尾,說明無環,則返回null
if (fast == null || fast.next == null) {
return null;
}
// 否則新開一個指針從表頭開始走,與slow同時走直到相遇。相遇點即爲所求
ListNode x = head;
while (x != slow) {
x = x.next;
slow = slow.next;
}
return x;
}
}
時間複雜度,空間。