Python3怎么实现判断环形链表算法
更新:HHH   时间:2023-1-7


这篇文章给大家分享的是有关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

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

返回开发技术教程...