class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next: #边界
return False
#初始化
slow = head
fast = head.next
while slow != fast:
#若走到尽头(注意fast肯定是走在前面的,用fast来检测,必须保证fast两步之内全部合法)
if not fast or not fast.next:
return False
slow = slow.next
fast = fast.next.next
return True
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next:
return False
slow = head
fast = head.next
while slow != fast:
#必须保证fast三步之内全部合法
if not fast or not fast.next or not fast.next.next:
return False
slow = slow.next.next
fast = fast.next.next.next
return True
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next: #边界
return False
#初始化
slow = head
fast = head
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False