给定一个链表,判断链表中是否有环。

示例:

输入1:

ListNode

输出1:

True

输入2:

ListNode

输出2:

False

解答:

def detectCycle(self, head):
    if head is None : return None
    if head.next is None : return None

    slow = fast = head
    steps = 0
    flag = False
    while(fast and fast.next):
        fast = fast.next.next
        slow = slow.next
        steps += 1
        if (fast == slow):
            flag = True
            break
    if not flag:
        return None
    else:
        while(head!=slow):
            slow = slow.next
            head = head.next
        return head