给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
本题比较我认为比较关键的在于使用快慢指针,如果链表中有环的话,快指针总会追上慢指针
public class Solution {
public ListNode detectCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
ListNode index1 = fast;
ListNode index2 = head;
while(index1 != index2){
index1 = index1.next;
index2 = index2.next;
}
return index1;
}
}
return null;
}
}