

迭代
思路:使用 Set 来保存每个节点,而形成环的地方就可以通过查询 Set 来看看是否有对应的元素即可:
/*** 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)* }* }*/function detectCycle(head: ListNode | null): ListNode | null {const set = new Set()let current = headwhile(current && current.next) {if (set.has(current.next)) {return current.next}set.add(current)current = current.next}return null};
复杂度分析:
- 时间复杂度:
- 空间复杂度:
