Python3怎么实现判断环形链表算法-创新互联

这篇文章给大家分享的是有关Python3怎么实现判断环形链表算法的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

创新互联是一家专业提供新华企业网站建设,专注与网站建设、网站设计成都h5网站建设、小程序制作等业务。10年已为新华众多企业、政府机构等服务。创新互联专业网络公司优惠进行中。

具体如下:

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

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

# 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

感谢各位的阅读!关于“Python3怎么实现判断环形链表算法”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!


标题名称:Python3怎么实现判断环形链表算法-创新互联
网站地址:http://myzitong.com/article/cciiih.html