142. 环形链表 II

2021-08-29  本文已影响0人  justonemoretry
image.png

解法

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if (head == null) {
            return null;
        }
        // 快慢指针
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) {
                // 相遇后,相遇点指针和头指针同时走,会走到环入口
                // 公式为(x+y)*2 = x + y + (y + z)* n
                // 当n为1时,x=z,不为1时,相遇点指针多转几圈
                while (fast != head) {
                    fast = fast.next;
                    head = head.next;
                }
                return head;
            }
        }
        return null;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读