[剑指Offer] 23_链表中环的入口节点

版权声明:Tian Run https://blog.csdn.net/u013908099/article/details/86164084

题目

如果一个链表中包含环,如何找出环的入口节点?

例:

1->2->3->4->5->6
    个__________|


思路

  1. 快慢指针相遇时找到环,并算出环长度,然后用一组间隔环长的双指针从头遍历链表,相遇时即为入口。
    1. 时间复杂度:O(n),最差情况入口在头节点,遍历2次链表。
    2. 空间复杂度:O(1)
  2. 如果链表有环,那么遍历列表将得到一个周期函数。LN(a + b - a) = LN(a + b + nT - a) T为环的长度,a为环之前的长度,b为环内走过的长度。
    此题即求a的值。双指针遍历Ps Pf,使Pf2倍快于Ps,那么总有Pf == Ps,的时候此时Ps = a + b; Pf = 2a + 2b;nT = a + b。因此,当Ps再走a步时,LN(Ps = a + b + a) =LN(a),此时一个从头出发的节点也正好走到LN(a)。此节点即为入口。
    1. 时间复杂度:O(n),比思路1快,只需要遍历1次链表。
    2. 空间复杂度: O(1)

代码

思路2:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None
def entry_node_in_list_loop(head):
    """    
    :param head: head
    :return: entry node
    """
    pos = None
    slow = fast = head
    while slow and fast and fast.next:
        slow = slow.next
        fast = fast.next.next
        if slow is fast:
            pos = head
            while pos is not slow:
                pos = pos.next
                slow = slow.next
            break
    return pos

思考

思路1容易想到,也比较直观,但是没有思路2快。思路2需要数学抽象方便理解。
LeetCode上有同样的题目,可以测试。

142. 环形链表 II

题目

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

说明:不允许修改给定的链表。

示例 1:

输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
Alt

示例 2:

输入:head = [1,2], pos = 0
输出:tail connects to node index 0
解释:链表中有一个环,其尾部连接到第一个节点。

alt

示例 3:

输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环。

alt

进阶:
你是否可以不用额外空间解决此题?

猜你喜欢

转载自blog.csdn.net/u013908099/article/details/86164084