方法一:快慢指针
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if slow == fast:
return True
return False
方法二:哈希表
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
record = dict()
p = head
while p:
if p not in record:
record[p] = 1
else:
return True
p = p.next
return False