题目
给定一个链表,判断链表中是否有环。
思路
也可以用哈希表,不过空间复杂度会是O(n)。
代码
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if head is None or head.next is None:
return False
slow = head
fast = head.next
while slow != fast:
if fast.next is None or fast.next.next is None:
return False
slow = slow.next
fast = fast.next.next
return True