判斷鏈表是否存在環,輸出第一次的環的入口地址

 參考鏈接:https://blog.csdn.net/yangnianjinxin/article/details/79025768

上面這個博客的鏈接有詳細的敘述過程,講得很好。

# -*- coding:utf-8 -*-


class Node():  # 定義一個Node類,構造兩個屬性,一個是item節點值,一個是節點的下一個指向
    def __init__(self, item=None):
        self.item = item
        self.next = None


def findbeginofloop(head):
    slow = head
    fast = head
    loopExist = False  # 默認環不存在,爲False
    if head == None:
        return False

    #判斷環是否存在
    while slow and fast and fast.next != None and fast.next.next != None:
        slow = slow.next
        fast = fast.next.next
        if slow == fast:
            loopExist = True
            print("存在環結構")
            break

    #這個時候fast是在相交的地方
    if loopExist == True:
        slow = head
        while slow != fast:
            fast = fast.next
            slow = slow.next
        return slow

    print("不存在環結構")
    return False


if __name__ == "__main__":
    node1 = Node(1)
    node2 = Node(2)
    node3 = Node(3)
    node4 = Node(4)
    node5 = Node(5)
    node6 = Node(6)
    node1.next = node2
    node2.next = node3
    node3.next = node4
    node4.next = node5
    node5.next = node6
    node5.next = node2
    node6.next = node3
    print(findbeginofloop(node1).item)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章