面试算法-159-环形链表 II-解

时间:2024-04-09 13:41:51
public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy;
        ListNode fast = head;
        while (fast != null && slow != fast) {
            slow = slow.next;
            fast = fast.next;
            if (fast != null) {
                fast = fast.next;
            }
        }
        if (slow != fast) {
            return null;
        }
        int countCycle = 1;
        ListNode p1 = slow.next;
        while (p1 != slow) {
            countCycle++;
            p1 = p1.next;
        }

        // 让p2和head保持环长度的距离,当进入环后,他们之间的距离正好包住环
        ListNode p2 = head;
        for (int i = 0; i < countCycle; i++) {
            p2 = p2.next;
        }
        while (p2 != head) {
            head = head.next;
            p2 = p2.next;
        }
        return head;
    }
}