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
相关推荐
阿华hhh18 小时前
数据结构(树)
linux·c语言·开发语言·数据结构
sin_hielo18 小时前
leetcode 3652(定长滑动窗口/前缀和)
数据结构·算法·leetcode
AI科技星18 小时前
质量定义方程中条数概念的解析与经典例子计算
数据结构·人工智能·经验分享·算法·计算机视觉
合方圆~小文18 小时前
四倍枪机日夜模式自动切换控制
数据结构·人工智能
LYFlied18 小时前
【每日算法】LeetCode 22. 括号生成
数据结构·算法·leetcode·面试·职场和发展
想自律的露西西★18 小时前
js.39. 组合总和
前端·javascript·数据结构·算法
zore_c18 小时前
【数据结构】栈——超详解!!!(包含栈的实现)
c语言·开发语言·数据结构·经验分享·笔记·算法·链表
月明长歌18 小时前
【码道初阶】【Leetcode105&106】用遍历序列还原二叉树:前序+中序、后序+中序的统一套路与“先建哪边”的坑
java·开发语言·数据结构·算法·leetcode·二叉树
iAkuya18 小时前
(leetcode)力扣100 16除自身以外数组的乘积(预处理前项后项积)
数据结构·算法·leetcode
不穿格子的程序员1 天前
从零开始写算法——链表篇4:删除链表的倒数第 N 个结点 + 两两交换链表中的节点
数据结构·算法·链表