python中怎么判斷鏈表是否有環(huán),很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
先看下實例代碼:
class Node: def __init__(self,value=None): self.value = value self.next = Noneclass LinkList: def __init__(self,head = None): self.head = head def get_head_node(self): """ 獲取頭部節(jié)點 """ return self.head def append(self,value) : """ 從尾部添加元素 """ node = Node(value = value) cursor = self.head if self.head is None: self.head = node else: while cursor.next is not None: cursor = cursor.next cursor.next = node if value==4: node.next = self.head def traverse_list(self): head = self.get_head_node() cursor = head while cursor is not None: print(cursor.value) cursor = cursor.next print("traverse_over") def hasCycle(self, head): """ :type head: ListNode :rtype: bool """ slow=fast=head while slow and fast and fast.next: slow = slow.next fast = fast.next.next if slow is fast: return True return Falsedef main(): l = LinkList() l.append(1) l.append(2) l.append(3) l.append(4) head = l.get_head_node() print(l.hasCycle(head)) #l.traverse_list()if __name__ == "__main__": main()
知識點思考:
判斷一個單鏈表是否有環(huán),
可以用 set 存放每一個 節(jié)點, 這樣每次 訪問后把節(jié)點丟到這個集合里面.
其實 可以遍歷這個單鏈表, 訪問過后,
如果這個節(jié)點 不在 set 里面, 把這個節(jié)點放入到 set 集合里面.
如果這個節(jié)點在 set 里面 , 說明曾經訪問過, 所以這個鏈表有重新 走到了這個節(jié)點, 因此一定有環(huán)
如果鏈表都走完了, 把所有的節(jié)點都放完了. 還是沒有重復的節(jié)點, 那說明沒有環(huán).
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)網站建設公司,的支持。
新聞標題:python中怎么判斷鏈表是否有環(huán)-創(chuàng)新互聯(lián)
網頁鏈接:http://aaarwkj.com/article48/dohpep.html
成都網站建設公司_創(chuàng)新互聯(lián),為您提供手機網站建設、虛擬主機、關鍵詞優(yōu)化、網站設計公司、定制開發(fā)、小程序開發(fā)
聲明:本網站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)