python判断链表是否有环
2023-09-14 09:06:35 时间
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):
"""
获取头部节点
"""
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()
相关文章
- python的time模块总结
- python实现矩阵乘法的方法
- 查看python中已安装的包有哪些
- python code practice(三):链表、栈、队列
- Python tkinter库之Canvas自定义直线函数画随机色彩圆盘
- Python爬虫开发:url中文字符编码的两种解决方式
- 华为OD机试 - 单向链表中间节点(Java & JS & Python)
- 用半励志的方式告诉你,怎么学习Python开发
- Python之pandas:将dict字典格式数据保存为dataframe格式数据的几种方法
- 〖Python零基础入门篇(54)〗- 文件的应用-序列化与反序列化
- 合并两个有序的链表Python和Go代码
- python 快速排序-代码示例
- 【LeetCode Python实现】19. 删除链表的倒数第 N 个结点(中等)首次 99.5% +
- 电脑中同时存在多个版本的Python,在指定版本中安装依赖库(值得学习)
- Python:inspect获取模块下的所有类对象
- Python编程:为世界贡献你的轮子-pipy打包
- python--文件操作删除某行
- python date time
- python如何发布自已pip项目
- 【Leetcode刷题Python】234.回文链表
- 【Leetcode刷题Python】203.移除链表元素
- 【Leetcode刷题Python】92.反转链表II
- 【Leetcode刷题Python】142.环形链表II
- 【Leetcode刷题Python】21. 合并两个有序链表
- 【Leetcode刷题Python】剑指 Offer 18. 删除链表的节点
- 路径规划算法 python 实现
- Python和Java哪个更好找工作?