当前位置: 移动技术网 > IT编程>脚本编程>Python > Python3实现的判断环形链表算法示例

Python3实现的判断环形链表算法示例

2019年03月19日  | 移动技术网IT编程  | 我要评论

剑客行ol,权利的游戏第四季05,我是米诺斯

本文实例讲述了python3实现的判断环形链表算法。分享给大家供大家参考,具体如下:

给定一个链表,判断链表中是否有环。

方案一:快慢指针遍历,若出现相等的情况,说明有环

# definition for singly-linked list.
# class listnode(object):
#   def __init__(self, x):
#     self.val = x
#     self.next = none
class solution(object):
  def hascycle(self, head):
    """
    :type head: listnode
    :rtype: bool
    """
    slow = fast = head
    while fast and fast.next:
      slow = slow.next
      fast = fast.next.next
      if fast == slow:
        return true
    return false

方案二:遍历链表,寻找.next=head的元素。 但超出时间限制

# definition for singly-linked list.
# class listnode(object):
#   def __init__(self, x):
#     self.val = x
#     self.next = none
class solution(object):
  def hascycle(self, head):
    """
    :type head: listnode
    :rtype: bool
    """
    if not head:
      return false
    cur = head.next
    while cur:
      if cur.next == head:
        return true
      cur = cur.next
    return false

更多关于python相关内容感兴趣的读者可查看本站专题:《python数据结构与算法教程》、《python加密解密算法与技巧总结》、《python编码操作技巧总结》、《python函数使用技巧总结》、《python字符串操作技巧汇总》及《python入门与进阶经典教程

希望本文所述对大家python程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网