LeetCode141.Linked List Cycle环形链表(Python可运行,带测试用例)

一、题目

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

二、题解

快慢指针

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None

def make_list(arr):
    head_node = None
    p_node = None
    for a in arr:
        new_node = ListNode(a)
        if head_node is None:
            head_node = new_node
            p_node = new_node
        else:
            p_node.next = new_node
            p_node = new_node
    return head_node

# def print_list(head):
#     while head is not None:
#         print(head.val, end=',')
#         head = head.next

class Solution:
    def hasCycle(self, head: ListNode) -> bool:
        slow = head
        fast = head
        # 无环,迟早退出
        while fast is not None and fast.next is not None:
            slow = slow.next# 慢指针每次走一步
            fast = fast.next.next# 快指针每次走两步
        # 有环,迟早遇到,返回True,快指针会在环中一直转
            if slow == fast:
                return True
        return  False



s = Solution()
a = [1,2,3,4,5]
head = make_list(a)
# 使第5个结点指向第3个结点,存在环形
head.next.next.next.next.next = head.next.next
# # 无法打印,死循环
# print_list(head)
print(s.hasCycle(head))

时间复杂度:O(N),其中 N是链表中的节点数。

  • 当链表中不存在环时,快指针将先于慢指针到达链表尾部,链表中每个节点至多被访问两次。
  • 当链表中存在环时,每一轮移动后,快慢指针的距离将减小一。而初始距离为环的长度,因此至多移动 N轮。

空间复杂度:O(1)。我们只使用了两个指针的额外空间。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值