代码一:快慢指针
class Solution(object):
# 快慢指针
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
slow, fast = head, head
finder = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
while finder != slow:
finder = finder.next
slow = slow.next
return finder
return None
代码二:list
class Solution(object):
# list
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
mylist = []
while head:
if head in mylist:
return head
else:
mylist.append(head)
head = head.next
return None