Given a linked list, determine if it has a cycle in it.
解答:定义两个指针分别从链表头部开始,一个指针每次走一步,另一个指针每次走两步,若两个指针所指的值相等,则说明有环,否则没环;要注意指针所指之处是否为空
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if head == None or head.next == None: # 判断是否为空
return False
slow = fast = head
while fast and fast.next:
slow = slow.next # 一次走一步
fast = fast.next.next # 一次走两步
if slow == fast:
return True
return False