给定一个链表,返回链表开始入环的第一个节点。 若是链表无环,则返回 null。node
为了表示给定链表中的环,咱们使用整数 pos 来表示链表尾链接到链表中的位置(索引从 0 开始)。 若是 pos 是 -1,则在该链表中没有环。指针
说明:不容许修改给定的链表。code
示例 1:blog
输入:head = [3,2,0,-4], pos = 1 输出:tail connects to node index 1 解释:链表中有一个环,其尾部链接到第二个节点。
示例 2:索引
输入:head = [1,2], pos = 0 输出:tail connects to node index 0 解释:链表中有一个环,其尾部链接到第一个节点。
示例 3:it
输入:head = [1], pos = -1 输出:no cycle 解释:链表中没有环。
进阶:
你是否能够不用额外空间解决此题?io
两种方法:
1,用哈希表,依次遍历链表set存储走过的点,碰见重复的就是环入口 ———— 时间复杂度O(n),空间复杂度O(n)
2,快慢指针,指针在环内相遇的位置到环入口的距离 == 表头到环入口的距离,二者相向而行,相遇位置就是环入口 ———— 时间复杂度O(n²),空间复杂度O(1)class
经过代码以下:List
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None # 哈希表:时间复杂度O(n),空间复杂度O(n) # class Solution: # def detectCycle(self, head: ListNode) -> ListNode: # s = set() # while head: # if head in s: # return head # s.add(head) # head = head.next # return None # 指针法:时间复杂度O(n²),空间复杂度O(1) # 1,快慢双指针找到相遇位置 # 2,相遇位置到环入口的距离 == 表头到环入口的距离,二者相向而行,相遇位置就是环入口 class Solution: def detectCycle(self, head: ListNode) -> ListNode: f = s = h = head # h记录表头 while f and f.next: s = s.next f = f.next.next if f == s: # 相遇了,开始和表头相对走,找环入口 p = f while h!=p: h = h.next p = p.next return h head = head.next return None