給定一個鏈表,返回鏈表開始入環的第一個節點。?如果鏈表無環,則返回?null。
為了表示給定鏈表中的環,我們使用整數 pos 來表示鏈表尾連接到鏈表中的位置(索引從 0 開始)。 如果 pos 是 -1,則在該鏈表中沒有環。
說明:不允許修改給定的鏈表。
?
示例 1:
輸入:head = [3,2,0,-4], pos = 1
輸出:tail connects to node index 1
解釋:鏈表中有一個環,其尾部連接到第二個節點。
示例?2:
輸入:head = [1,2], pos = 0
輸出:tail connects to node index 0
解釋:鏈表中有一個環,其尾部連接到第一個節點。
示例 3:
輸入:head = [1], pos = -1
輸出:no cycle
解釋:鏈表中沒有環。
思路:
慢指針一次一步,快指針一次兩步。能相遇就是有環,反之沒有環。
讓一個指針從頭走,另一個從相遇點開始走,然后再次相遇的地方就是入環點,不明白的畫一畫,想一想操場跑步就明白了。
/*** Definition for singly-linked list.* class ListNode {* int val;* ListNode next;* ListNode(int x) {* val = x;* next = null;* }* }*/
public class Solution {private ListNode getIntersect(ListNode head) {ListNode tortoise = head;ListNode hare = head;while (hare != null && hare.next != null) {tortoise = tortoise.next;hare = hare.next.next;if (tortoise == hare) {return tortoise;}}return null;
}public ListNode detectCycle(ListNode head) {if (head == null) {return null;}ListNode intersect = getIntersect(head);if (intersect == null) return null;ListNode ptr1 = head;ListNode ptr2 = intersect;while (ptr1 != ptr2) {ptr1 = ptr1.next;ptr2 = ptr2.next;}return ptr1;}
}