*python3__leecode/0141.环型链表


一、刷题内容

原题链接

https://leetcode-cn.com/problems/linked-list-cycle/

内容描述

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

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:
输入:head = [1,2], pos = 0
输出:true
解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:
输入:head = [1], pos = -1
输出:false
解释:链表中没有环。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

解释:
上面示例中的 pos,是无关我们的变量,告诉我们链尾是指向 第pos个元素的

二、解题方案

1.方法一:字典

通过检查一个结点此前是否被访问过来判断链表是否为环形链表,通常用哈希表,这里用了字典。

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        lookup = {}
        while head:
            if head not in lookup:
                lookup[head] = 1  # 字典中可以直接将head作为key,key值为存储的引用
            else:
                return True
            
            head = head.next
        return False

2.方法二:快慢双指针

对于一个环,快指针移动的比慢指针快,总是会追上慢指针,反之无环,快指针终点

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if head == None or head.next == None:
            return False

        slow = head  # 慢指针
        fast = head.next  # 快指针

        while slow != fast:
            if fast == None or fast.next == None:
                return False
            
            slow = slow.next  # 慢指针一次移动一个节点
            fast = fast.next.next  # 快指针一次移动两个节点
        
        return True

3.方法三:快慢双指针

这个效率比上面的高和简洁

class Solution(object):
    def hasCycle(self, head):
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if fast == slow:  # 快指针追上慢指针,有环返回
                return True
        return False

4.方法四:暴力破坏链表

一般解法还是快慢指针和哈希表

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        while head and head.val != None: 
            head.val, head = None, head.next
        return head != None
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

百里 Jess

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值