python判斷鏈表是否有環(huán)的實(shí)例代碼
先看下實(shí)例代碼:
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é)點(diǎn)
"""
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()
知識點(diǎn)思考:
判斷一個單鏈表是否有環(huán),
可以用 set 存放每一個 節(jié)點(diǎn), 這樣每次 訪問后把節(jié)點(diǎn)丟到這個集合里面.
其實(shí) 可以遍歷這個單鏈表, 訪問過后,
如果這個節(jié)點(diǎn) 不在 set 里面, 把這個節(jié)點(diǎn)放入到 set 集合里面.
如果這個節(jié)點(diǎn)在 set 里面 , 說明曾經(jīng)訪問過, 所以這個鏈表有重新 走到了這個節(jié)點(diǎn), 因此一定有環(huán)
如果鏈表都走完了, 把所有的節(jié)點(diǎn)都放完了. 還是沒有重復(fù)的節(jié)點(diǎn), 那說明沒有環(huán).
以上就是本次介紹的全部相關(guān)知識點(diǎn)內(nèi)容,感謝大家的學(xué)習(xí)和對腳本之家的支持。
- python實(shí)現(xiàn)數(shù)據(jù)結(jié)構(gòu)中雙向循環(huán)鏈表操作的示例
- python操作鏈表的示例代碼
- python/golang 刪除鏈表中的元素
- python/golang實(shí)現(xiàn)循環(huán)鏈表的示例代碼
- python的鏈表基礎(chǔ)知識點(diǎn)
- 用python介紹4種常用的單鏈表翻轉(zhuǎn)的方法小結(jié)
- Python實(shí)現(xiàn)鏈表反轉(zhuǎn)的方法分析【迭代法與遞歸法】
- Python實(shí)現(xiàn)隊列的方法示例小結(jié)【數(shù)組,鏈表】
- python實(shí)現(xiàn)從尾到頭打印單鏈表操作示例
- Python棧的實(shí)現(xiàn)方法示例【列表、單鏈表】
- Python單鏈表原理與實(shí)現(xiàn)方法詳解
- python如何對鏈表操作
相關(guān)文章
Python實(shí)現(xiàn)批量生成,重命名和刪除word文件
這篇文章主要為大家詳細(xì)介紹了Python如何利用第三方庫實(shí)現(xiàn)批量生成、重命名和刪除word文件的功能,文中的示例代碼講解詳細(xì),需要的可以參考一下2023-03-03
OpenCV實(shí)現(xiàn)去除背景識別的方法總結(jié)
這篇文章主要為大家詳細(xì)介紹了如何利用OpenCV實(shí)現(xiàn)去除背景識別的功能,文中為大家總結(jié)了一些方法,感興趣的小伙伴快跟隨小編一起學(xué)習(xí)一下2022-10-10
python3.10及以上版本編譯安裝ssl模塊的詳細(xì)過程
最近搞安裝ssl模塊每天都弄到很晚,所以這里給大家整理下,這篇文章主要給大家介紹了關(guān)于python3.10及以上版本編譯安裝ssl模塊的詳細(xì)過程,文中介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
用Python編寫個解釋器實(shí)現(xiàn)方法接受
計算機(jī)只能理解機(jī)器碼。歸根結(jié)底,編程語言只是一串文字,目的是為了讓人類更容易編寫他們想讓計算機(jī)做的事情。真正的魔法是由編譯器和解釋器完成,它們彌合了兩者之間的差距。解釋器逐行讀取代碼并將其轉(zhuǎn)換為機(jī)器碼2023-01-01
Python基礎(chǔ)學(xué)習(xí)之反射機(jī)制詳解
在Python中,反射是指通過一組內(nèi)置的函數(shù)和語句,在運(yùn)行時動態(tài)地訪問、檢查和修改對象的屬性、方法和類信息的機(jī)制。本文將通過簡單的示例和大家講講Python中的反射機(jī)制,希望對大家有所幫助2023-03-03

