题目
给定一个链表,判断链表中是否有环。
思路
也可以用哈希表,不过空间复杂度会是O(n)。

代码
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = Noneclass Solution:def hasCycle(self, head: ListNode) -> bool:if head is None or head.next is None:return Falseslow = headfast = head.nextwhile slow != fast:if fast.next is None or fast.next.next is None:return Falseslow = slow.nextfast = fast.next.nextreturn True
