Leetcode刷题Python142.环形链表II

Posted Better Bench

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode刷题Python142.环形链表II相关的知识,希望对你有一定的参考价值。

一、题目描述
给定一个链表,返回链表开始入环的第一个节点。

如果链表无环,则返回 null。为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。

如果 pos 是 -1,则在该链表中没有环。

注意,pos 仅仅是用于标识环的情况,并不会作为参数传递到函数中。

说明:不允许修改给定的链表。

2 解析

需要双指针,一个fast,一个slow,需要实现两次fast slow,返回slow。在第一个次fastslow之前,fast每次走两步,slow走一步;之后fast和slow都各走一步,直到fast==slow,返回slow。





3 python 实现


class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        fast,slow = head,head
        while True:
            if not (fast and fast.next):return
            fast,slow = fast.next.next,slow.next
            if fast==slow:
                break
        fast = head
        while fast!=slow:
            fast,slow = fast.next,slow.next
        return slow
            

以上是关于Leetcode刷题Python142.环形链表II的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode刷题笔记之链表篇142. 环形链表 II

Leetcode刷题笔记之链表篇142. 环形链表 II

算法热门:环形链表II(LeetCode 142)

LeetCode第142题—环形链表II—Python实现

LeetCode刷题模版:141 - 150

LeetCode刷题模版:141 - 150