142. 环形链表 II
快慢指针
思路
fast = head, slow = head,每次循环,fast 走两步,slow 走一步。
若链表存在环,fast 与 slow 一定相遇;若不存在环,fast = null。
当 fast 与 slow 相遇时,一定存在环,此时令 index1 = fast,index2 = head,同步移动,相遇处即入环结点。
public class Solution {public ListNode detectCycle(ListNode head) {ListNode slow = head;ListNode fast = head;while (fast != null && fast.next != null) {slow = slow.next;fast = fast.next.next;// 若存在环,则快慢指针一定会相遇if (slow == fast) {ListNode index1 = fast;ListNode index2 = head;// 若存在环,index1与index2同步移动,相遇处即为入环结点while (index1 != index2) {index1 = index1.next;index2 = index2.next;}return index1;}}return null;}
}