美文网首页
142. 环形链表 II

142. 环形链表 II

作者: justonemoretry | 来源:发表于2021-08-29 22:08 被阅读0次
    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;
        }
    }
    

    相关文章

      网友评论

          本文标题:142. 环形链表 II

          本文链接:https://www.haomeiwen.com/subject/hmcpiltx.html