判断单向列表是否包括环,若包含,环入口的节点和环长计算

''' 判断单向列表是否包括环,若包含,环入口的节点和环长计算 '''

#定义链表
class ListNode():
    def __init__(self, val=None):
        self.val = val
        self.next = next

#判断链表是否有环(如果没有环则输出False,如果有环则输出(环的入口点地址,环入口点值,环长))
def findloop(head):
    loopExist = False
    if head == None:
        print('no exist loop!')
        return loopExist
    slow = head
    fast = head
    slowstepnum = 0 #记录slow从开始到相遇走的步长
    faststepnum = 0 #记录fast从开始到相遇走的步长
    while fast.next != None and fast.next.next!=None:
        slow = slow.next
        fast = fast.next.next
        slowstepnum += 1
        faststepnum += 2
        if slow == fast:
            loopExist = True
            print('exist loop!')
            break
    looplength = faststepnum - slowstepnum #环长 = fast走的步长 - slow走的步长 
    #判断环入口点(相遇点到环入口点和开始点到环入口点长度相同)
    if loopExist:
        slow = head
        while slow != fast:
            slow = slow.next
            fast = fast.next
        return (slow, slow.val, looplength)

    print('no exist loop!')
    return loopExist    

if __name__ == "__main__":  
    L1 = ListNode(1)        
    L2 = ListNode(2) 
    L3 = ListNode(3) 
    L4 = ListNode(4) 
    L5 = ListNode(5) 
    L6 = ListNode(6) 
    L7 = ListNode(7) 
    L8 = ListNode(8)    
    L1.next = L2
    L2.next = L3
    L3.next = L4
    L4.next = L5
    L5.next = L6
    L6.next = L7
    L7.next = L8
    L8.next = L3
    print(findloop(L1))




    原文作者:微微心情smile
    原文地址: https://blog.csdn.net/u012564409/article/details/79565346
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞