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
相关推荐
shylyly_1 小时前
stack/queue中的deque
数据结构·c++·deque·双端队列·queue·stack·容器适配器
土司大王2 小时前
LeetCode hot100——缺失的第一个正数
数据结构·算法·leetcode
铅笔小新z3 小时前
【数据结构】顺序表和链表
数据结构·链表
不会就选b3 小时前
数据结构之栈的算法题(OJ)
linux·数据结构·算法
漂流瓶jz4 小时前
UVA-1609 不公平竞赛 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·链表·贪心·aoapc·算法竞赛入门经典·uva
hzxpaipai4 小时前
制造业官网产品信息架构怎么设计?从产品分类到后台数据结构
大数据·数据结构
专注API从业者4 小时前
Open‑Claw 实战|无需逆向,快速搭建电商商品监控与数据分析系统
开发语言·数据结构·数据库·数据分析·php
纪念 2295 小时前
数据结构排序(四)
开发语言·数据结构
SelectDB技术团队6 小时前
统一全文检索与 SQL 分析:Apache Doris 日志分析实践
大数据·数据结构·后端·python·全文检索·doris·日志分析
凉茶钱6 小时前
【数据结构】计数排序
数据结构·算法·排序算法