141. 环形链表
用集合
class Solution:
def hasCycle(self, head: ListNode) -> bool:
aset = set()
while head:
if head in aset:
return True
aset.add(head)
head = head.next
return False
快指针+慢指针
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
class Solution:
def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False