leetcode142. 环形链表 II

leetcode142. 环形链表 II

题目

思路

集合法

  • 将节点存入set,若重复出现则说明是环

快慢指针法

  • 分别定义 fast 和 slow 指针,从头结点出发,fast指针每次移动两个节点,slow指针每次移动一个节点,如果 fast 和 slow指针在途中相遇 ,说明这个链表有环。
  • 初次相遇后,将slow设为头结点,slow和fast这两个指针每次只走一个节点, 当这两个指针相遇的时候就是环形入口的节点。

代码

集合法

python 复制代码
class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
        node_set = set()
        current = head
        while current:
            if current in node_set:
                return current
            else:
                node_set.add(current)
                current = current.next
        return None

快慢指针法

python 复制代码
class Solution:
    def detectCycle(self, head: ListNode) -> ListNode:
        slow = head
        fast = head
        
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            
            # If there is a cycle, the slow and fast pointers will eventually meet
            if slow == fast:
                # Move one of the pointers back to the start of the list
                slow = head
                while slow != fast:
                    slow = slow.next
                    fast = fast.next
                return slow
        # If there is no cycle, return None
        return None
相关推荐
gugucoding12 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL14 小时前
我的数据结构3——链表(link list)
数据结构·链表
王老师青少年编程15 小时前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月
Yang_jie_0315 小时前
笔记:数据结构(C语言版)第一章知识点详细归纳
c语言·数据结构·算法
海清河晏11116 小时前
数据结构 | 二叉搜索树
数据结构·c++·visual studio
Yang_jie_0316 小时前
笔记:数据结构(顺序表)
数据结构·windows·笔记
一个初入编程的小白21 小时前
数据结构:栈
数据结构
我命由我1234521 小时前
方差(实例实操、与标准差的区别)
java·数据结构·算法·数据分析·java-ee·intellij-idea·idea
努力努力再努力wz1 天前
【高性能网络库与HTTP Server系列】:基于主从 Reactor 模型实现高性能 C++ 网络库与 HTTP Server
开发语言·网络·数据结构·数据库·c++·网络协议·http
什巳1 天前
JAVA练习275-乘积最大子数组
java·开发语言·数据结构·算法