python判斷鏈表是否有環(huán)的實例代碼
先看下實例代碼:
class Node: def __init__(self,value=None): self.value = value self.next = None class 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 False def 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 里面 , 說明曾經(jīng)訪問過, 所以這個鏈表有重新 走到了這個節(jié)點, 因此一定有環(huán)
如果鏈表都走完了, 把所有的節(jié)點都放完了. 還是沒有重復(fù)的節(jié)點, 那說明沒有環(huán).
以上就是本次介紹的全部相關(guān)知識點內(nèi)容,感謝大家的學(xué)習(xí)和對腳本之家的支持。
- python實現(xiàn)數(shù)據(jù)結(jié)構(gòu)中雙向循環(huán)鏈表操作的示例
- python操作鏈表的示例代碼
- python/golang 刪除鏈表中的元素
- python/golang實現(xiàn)循環(huán)鏈表的示例代碼
- python的鏈表基礎(chǔ)知識點
- 用python介紹4種常用的單鏈表翻轉(zhuǎn)的方法小結(jié)
- Python實現(xiàn)鏈表反轉(zhuǎn)的方法分析【迭代法與遞歸法】
- Python實現(xiàn)隊列的方法示例小結(jié)【數(shù)組,鏈表】
- python實現(xiàn)從尾到頭打印單鏈表操作示例
- Python棧的實現(xiàn)方法示例【列表、單鏈表】
- Python單鏈表原理與實現(xiàn)方法詳解
- python如何對鏈表操作
相關(guān)文章
Python的Pillow庫進(jìn)行圖像文件處理(圖文詳解)
本文詳解的講解了使用Pillow庫進(jìn)行圖片的簡單處理,使用PyCharm開發(fā)Python的詳細(xì)過程和各種第三方庫的安裝與使用。感興趣的可以了解一下2021-11-11Python 實現(xiàn)隨機(jī)數(shù)詳解及實例代碼
這篇文章主要介紹了Python 實現(xiàn)隨機(jī)數(shù)詳解及實例代碼的相關(guān)資料,需要的朋友可以參考下2017-04-04pycocotools介紹以及在windows10下的安裝過程
這篇文章主要介紹了pycocotools介紹以及在windows10下的安裝過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02