判斷單向列表是否包括環,若包含,環入口的節點計算 python實現


 

關於數據結構相關的面試題,經常會問到鏈表中是否存在環結構的判斷,下圖就是存在環結構的鏈表。

那么如何判斷鏈表中是否存在環呢,下面解法的思路是采用快慢指針:

兩個指向頭節點的指針,fastslow,一起從頭結點開始往后遍歷,fast每次移動兩個節點,slow每次移動一個節點,

這樣,如果存在環結構,那么fast指針在不斷繞環過程中,肯定會追上slow指針。

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

 def findbeginofloop(head):#判斷是否為環結構並且查找環結構的入口節點
     slowPtr = head         #將頭節點賦予slowPtr
     fastPtr = head         #將頭節點賦予fastPtr
     loopExist =False       #默認環不存在,為False
     if head == None:       #如果頭節點就是空的,那肯定就不存在環結構
         return False
     while fastPtr.next != None and fastPtr.next.next != None:      #fastPtr的下一個節點和下下個節點都不為空
         slowPtr = slowPtr.next           #slowPtr每次移動一個節點
         fastPtr = fastPtr.next.next      #fastPtr每次移動兩個節點 
         if slowPtr == fastPtr :          #當fastPtr和slowPtr的節點相同時,也就是兩個指針相遇了
             loopExist = True
             print("存在環結構")
             break

     if loopExist == True:
         slowPtr  = head
         while slowPtr != fastPtr:
             fastPtr = fastPtr.next
             slowPtr = slowPtr.next
         return slowPtr

     print("不是環結構")
     return False

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM