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
相关推荐
不会就选b11 小时前
数据结构之顺序表和链表的OJ题(上)
数据结构·链表
啦啦啦啦啦zzzz14 小时前
数据结构:二叉树的线索化
数据结构·算法
如竟没有火炬15 小时前
寻找峰值——二分
java·开发语言·数据结构·python·算法·散列表
he___H17 小时前
B、B+树和vue部分知识
数据结构·vue.js·b树
hai31524754318 小时前
结构化编程:AI工业化编程的探索
数据结构·自然语言处理·硬件工程·动态规划·集成学习
2401_8685347818 小时前
2026年5月系统分析
数据结构·python·tornado
袋鼠云数栈20 小时前
数栈 V7.0 多模态数据智能平台:打造 AI-Ready 的企业数据底座
大数据·数据结构·数据库·人工智能·数据治理·多模态
迈巴赫车主20 小时前
优先队列(PriorityQueue)
数据结构·算法
Boom_Shu20 小时前
构造函数程序
数据结构·算法
Lucky_ldy21 小时前
数据结构从入门到精通:链表
数据结构·链表