题目

给定一个链表,判断链表中是否有环。

思路

也可以用哈希表,不过空间复杂度会是O(n)。
image.png
image.png

代码

  1. # Definition for singly-linked list.
  2. # class ListNode:
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.next = None
  6. class Solution:
  7. def hasCycle(self, head: ListNode) -> bool:
  8. if head is None or head.next is None:
  9. return False
  10. slow = head
  11. fast = head.next
  12. while slow != fast:
  13. if fast.next is None or fast.next.next is None:
  14. return False
  15. slow = slow.next
  16. fast = fast.next.next
  17. return True