python判断链表是否有环的实例代码

前端之家收集整理的这篇文章主要介绍了python判断链表是否有环的实例代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

先看下实例代码

  1. class Node:
  2. def __init__(self,value=None):
  3. self.value = value
  4. self.next = None
  5.  
  6. class LinkList:
  7. def __init__(self,head = None):
  8. self.head = head
  9.  
  10. def get_head_node(self):
  11. """
  12. 获取头部节点
  13. """
  14. return self.head
  15.  
  16. def append(self,value) :
  17. """
  18. 从尾部添加元素
  19. """
  20. node = Node(value = value)
  21. cursor = self.head
  22. if self.head is None:
  23. self.head = node
  24. else:
  25. while cursor.next is not None:
  26. cursor = cursor.next
  27.  
  28. cursor.next = node
  29. if value==4:
  30. node.next = self.head
  31.  
  32. def traverse_list(self):
  33. head = self.get_head_node()
  34. cursor = head
  35. while cursor is not None:
  36. print(cursor.value)
  37. cursor = cursor.next
  38. print("traverse_over")
  39.  
  40. def hasCycle(self,head):
  41. """
  42. :type head: ListNode
  43. :rtype: bool
  44. """
  45. slow=fast=head
  46. while slow and fast and fast.next:
  47. slow = slow.next
  48. fast = fast.next.next
  49. if slow is fast:
  50. return True
  51. return False
  52.  
  53. def main():
  54. l = LinkList()
  55. l.append(1)
  56. l.append(2)
  57. l.append(3)
  58. l.append(4)
  59. head = l.get_head_node()
  60. print(l.hasCycle(head))
  61. #l.traverse_list()
  62.  
  63. if __name__ == "__main__":
  64. main()

知识点思考:

判断一个单链表是否有环,

可以用 set 存放每一个 节点,这样每次 访问后把节点丢到这个集合里面.

其实 可以遍历这个单链表,访问过后,

如果这个节点 不在 set 里面,把这个节点放入到 set 集合里面.

如果这个节点在 set 里面,说明曾经访问过,所以这个链表有重新 走到了这个节点,因此一定有环

如果链表都走完了,把所有的节点都放完了. 还是没有重复的节点,那说明没有环.

以上就是本次介绍的全部相关知识点内容,感谢大家的学习和对我们的支持

猜你在找的Python相关文章