Const
给定一个链表的头节点 head,返回链表开始入环的第一个节点。如果链表无环,则返回 null。
head
null
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。为了表示给定链表中的环,输入格式中使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。如果 pos 是 -1,则在该链表中没有环。
next
pos
注意: pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。
输入: head = [3,2,0,-4], pos = 1 输出: tail connects to node index 1 解释: 链表中有一个环,其尾部连接到第二个节点。
head = [3,2,0,-4], pos = 1
tail connects to node index 1
输入: head = [1,2], pos = 0 输出: tail connects to node index 0 解释: 链表中有一个环,其尾部连接到第一个节点。
head = [1,2], pos = 0
tail connects to node index 0
输入: head = [1], pos = -1 输出: no cycle 解释: 链表中没有环。
head = [1], pos = -1
no cycle
[0, 10^4]
-10^5 <= Node.val <= 10^5
-1
Definition for singly-linked list. class ListNode { val: number next: ListNode | null constructor(val?: number, next?: ListNode | null) { this.val = (val===undefined ? 0 : val) this.next = (next===undefined ? null : next) } }
和第一个题型一样,用set记录遍历过的节点,如果遍历到set中存在的节点,说明有环。直接返回该节点
142.环形链表 II
给定一个链表的头节点
head
,返回链表开始入环的第一个节点。如果链表无环,则返回null
。如果链表中有某个节点,可以通过连续跟踪
next
指针再次到达,则链表中存在环。为了表示给定链表中的环,输入格式中使用整数pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。如果pos
是 -1,则在该链表中没有环。注意:
pos
仅仅是用于标识环的情况,并不会作为参数传递到函数中。示例 1:
输入:
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:
输入:
head = [1], pos = -1
输出:no cycle
解释: 链表中没有环。提示:
[0, 10^4]
-10^5 <= Node.val <= 10^5
pos
为-1
或者链表中的一个有效索引。