自学内容网 自学内容网

LeetCode[中等] 142. 环形链表 II

给定一个链表的头节点  head ,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

不允许修改 链表。

思路:

fast = 2 * slow
slow = a + n*b - c // 假设 slow 走了 n 圈
fast = a + m*b - c // 假设 fast 走了 m 圈
那就有:
a + m*b - c = 2*(a + n*b - c)
继而得到:
a = c + (m-n)*b
而(m-n)*b表示走了 m-n 圈,不影响 c 的大小,即可忽略,最终得到:
a = c

通过上面的推导,我们知道相遇点距环的入口的距离(c)与开头到环的入口的距离(a)相等。

因此当 fast 与 slow 相遇时,只要 fast 重新定位到表头,与 slow 一起走,当它们再次相遇时,就是环的入口。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode DetectCycle(ListNode head) {
        ListNode fast = head, slow = head;
        while(fast != null && fast.next != null)
        {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow)
            {
                fast = head;
                while(fast != slow)
                {
                    fast = fast.next;
                    slow = slow.next;
                }
                return fast;
            }
        }
        return null;
    }
}

复杂度分析 

  • 时间复杂度:O(n),其中 n 是链表长度
  • 空间复杂度:O(1)

原文地址:https://blog.csdn.net/Theolulu/article/details/142349550

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!