python判斷鏈表是否有環(huán)的實例代碼
更新時間:2020年01月31日 10:00:44 作者:一起來學python
在本篇文章里小編給大家整理的是關于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 里面 , 說明曾經訪問過, 所以這個鏈表有重新 走到了這個節(jié)點, 因此一定有環(huán)
如果鏈表都走完了, 把所有的節(jié)點都放完了. 還是沒有重復的節(jié)點, 那說明沒有環(huán).
以上就是本次介紹的全部相關知識點內容,感謝大家的學習和對腳本之家的支持。
您可能感興趣的文章:
- python實現(xiàn)數(shù)據結構中雙向循環(huán)鏈表操作的示例
- python操作鏈表的示例代碼
- python/golang 刪除鏈表中的元素
- python/golang實現(xiàn)循環(huán)鏈表的示例代碼
- python的鏈表基礎知識點
- 用python介紹4種常用的單鏈表翻轉的方法小結
- Python實現(xiàn)鏈表反轉的方法分析【迭代法與遞歸法】
- Python實現(xiàn)隊列的方法示例小結【數(shù)組,鏈表】
- python實現(xiàn)從尾到頭打印單鏈表操作示例
- Python棧的實現(xiàn)方法示例【列表、單鏈表】
- Python單鏈表原理與實現(xiàn)方法詳解
- python如何對鏈表操作
相關文章
Python 實現(xiàn)隨機數(shù)詳解及實例代碼
這篇文章主要介紹了Python 實現(xiàn)隨機數(shù)詳解及實例代碼的相關資料,需要的朋友可以參考下2017-04-04
pycocotools介紹以及在windows10下的安裝過程
這篇文章主要介紹了pycocotools介紹以及在windows10下的安裝過程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-02-02

