手撕算法系列——4. 判断单链表是否有环

本文介绍了如何使用双指针法判断单链表是否存在环,以及如何找到环的入口和长度。通过设置一个指针每次移动一步,另一个移动两步,当它们相遇时确定存在环。若要找入口,可以从头节点和相遇节点同时开始,每次移动一步,再次相遇即为入口。环的长度则在相遇后,一个指针继续移动并计数,再次相遇时的步数即为环的长度。这种方法还可用于判断无环链表的交点。

    这道题展开来说,就是给出一个单链表的头结点head:

    1)求该链表中是否存在环路;

    2)如果存在环路,求出环路的入口和环的长度。

    根据单链表的性质,一个结点最多只能有一个后继,故单链表若存在环,则环一定在链表的末尾,且没有尾结点。如果一直沿着链表遍历下去,最后会在环内一直死循环。

    根据以上性质,这道题的解法还是用“双指针”的思想,两个指针同时从头结点出发,但是一个指针(slow)一次走一步,另一个(fast)一次走两步,这样一来,如果链表中存在环,最后这两个结点一定会在环中相遇;若没有环,则slow一定永远不能和fast相遇。

    根据以上思想,用Python实现如下:

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def is_loop(head : ListNode):
    if head is None or head.next is None:
        return False           #空链表或只有一个结点的链表一定没有环
    slow = head.next
    fast = head.next.next
    while fast.next is not None and fast is not None:
        slow = slow.next
        fast = fast.next.next
        if fast is slow:
            return True
    return False

    如果要寻找环的入口点,则需对上述算法稍加改进,可以证明,如果单链表存在环,设上述的slow和fast相遇时两者指向结点A,则A到环的入口的步长等于head到入口的步长,因此在判断有环的基础上,让两个指针分别从head和相遇结点A出发,两者每次都只走一步,这样当两者再次相遇时,其指向的结点就是环的入口结点了。改进后的算法如下:

def is_loop(head : ListNode):
    """
    :return: if there is a loop in the list, return the start node of the loop
    if not, return None
    """
    if head is None or head.next is None:
        return None
    slow = head.next
    fast = head.next.next
    while fast.next is not None and fast is not None:
        slow = slow.next
        fast = fast.next.next
        if fast is slow:
            slow = head
            while True:
                slow = slow.next
                fast = fast.next
                if slow is fast:
                    return slow
    return None

    如果要求环的长度就很简单了,两者相遇后,让fast停下,slow继续走,走的时候记步,等到两者再次相遇后记录的步数就是环的长度了。算法如下:

def is_loop(head : ListNode):
    """
    :return: if there is a loop in the list, return the length of the loop
    if not, return None
    """
    if head is None or head.next is None:
        return None
    slow = head.next
    fast = head.next.next
    while fast.next is not None and fast is not None:
        slow = slow.next
        fast = fast.next.next
        if fast is slow:
            count = 0
            while True:
                slow = slow.next
                count += 1
                if slow is fast:
                    return count
    return None

    此外,这个算法还可以用于判断两条无环链表是否存在交点,原理很简单,把一条链表首尾相接形成一个环,用上述算法判断另一条链表中是否有环,如果有环,说明两条链表有交点,且环的入口就是两者的交点,算法如下:

def getIntersectionNode(headA, headB):
        """
        if there is an intersection node of listA and listB, return the intersection node, else return None
        """
        if headA is None:
            return None    #快速排斥:空链表不会有交点
        if headA is headB:
            return headA    #快速排斥:如果两者起点相同,则起点就是交点
        endA = headA
        while endA.next is not None:
            endA = endA.next
            if endA is headB:
                return endA    #快速排斥:如果B是A一部分,则B的头结点就是交点
        endA.next = headA
        r = is_loop(headB)    #这里用的是返回环的入口结点的函数
        endA.next = None
        return r



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值