# Definition for singly-linked list.# class ListNode(object):# def __init__(self, x):# self.val = x# self.next = NoneclassSolution(object):defhasCycle(self,head):""" :type head: ListNode :rtype: bool """ifnotheadornothead.next:# 0 or 1 itemreturnFalseslow=headfast=head# >2 item, omit the first time that slow == fastslow=slow.nextfast=fast.next.nextwhilefastandfast.next:# do not judge slow, since fast ahead of slow is trueslow=slow.next# slow cursor move one stepfast=fast.next.next# fast cursor move two stepsiffast==slow:returnTrue# fast cross circle twice and reaches the slowreturnFalse# fast reaches the end
近期评论