image.png
image.png

迭代

思路:使用 Set 来保存每个节点,而形成环的地方就可以通过查询 Set 来看看是否有对应的元素即可:

  1. /**
  2. * Definition for singly-linked list.
  3. * class ListNode {
  4. * val: number
  5. * next: ListNode | null
  6. * constructor(val?: number, next?: ListNode | null) {
  7. * this.val = (val===undefined ? 0 : val)
  8. * this.next = (next===undefined ? null : next)
  9. * }
  10. * }
  11. */
  12. function detectCycle(head: ListNode | null): ListNode | null {
  13. const set = new Set()
  14. let current = head
  15. while(current && current.next) {
  16. if (set.has(current.next)) {
  17. return current.next
  18. }
  19. set.add(current)
  20. current = current.next
  21. }
  22. return null
  23. };

复杂度分析:

  • 时间复杂度:142. 环形链表 II - 图3
  • 空间复杂度:142. 环形链表 II - 图4