Python 判断链表中是否有环

Python 判断链表中是否有环

解题思路:

  • 定义快慢指针,fast指针步长为2,slow指针步长为1,如果有环,两个指针必定相遇,即fast指针一定追上slow指针;就比如两个人在操场跑圈,一个跑的快,一个跑的慢,操场好比一个环,跑的快的人一定会追上跑的慢的人(超圈了)

python代码实现

def is_circle(head):
    # 空链表或者链表只有一个节点的情况
    if head is None or head.next is None:
        return False

    slow = head
    fast = head

    while fast is not None and fast.next is not None:
        fast = fast.next.next   # fast步长为2
        slow = slow.next        # slow步长为1

        if fast == slow:
            return True

    return False

猜你喜欢

转载自blog.csdn.net/weixin_44912159/article/details/115341967