方法一思路:
快慢指针。
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
方法二思路:
用list或set。
class Solution(object):
def hasCycle2(self, head):
"""
:type head: ListNode
:rtype: bool
"""
list = []
while head:
if head in list:
return True
list.append(head)
head = head.next
return False