# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defhasCycle(self, head: ListNode)->bool:ifnot head:# 空链表和空树都要预防returnFalse
ls =[]
ls.append(head)
cur = head.nextwhile cur and(cur notin ls):
ls.append(cur)
cur = cur.nextifnot cur:# 当没有环时returnFalsereturnTrue# 存在环时
时间复杂度:
O
(
n
)
O(n)
O(n)
空间复杂度:
O
(
n
)
O(n)
O(n)
3.官方的解决方案
想不出来
O
(
1
)
O(1)
O(1),所以主要积累官方做法
这个是判断链表有没有环最普遍的方法
# Definition for singly-linked list.# class ListNode:# def __init__(self, x):# self.val = x# self.next = NoneclassSolution:defhasCycle(self, head: ListNode)->bool:# 使用快慢指针法ifnot head:# 先解决空链表的情况returnFalse
slow = head
fast = head
while fast and fast.next:# 速度不一,间距一直在缩小,有环则两者相遇,没环,提前结束
slow = slow.next# 以一个结点为步长
fast = fast.next.next# 以两个结点为步长if slow == fast:returnTruereturnFalse