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
相关推荐
All for pursuit.36 分钟前
【二分查找-2】34.在排序数组中查找元素的第一个和最后一个位置
数据结构·c++·算法·leetcode
bro_Java6661 小时前
链表进阶2:双向链表的构建
java·数据结构·链表
梦帮科技2 小时前
量子张量网络破局大模型:从矩阵乘积态 (MPS) 到张量列 (TT-SVD) 低秩收缩全推导
网络·数据结构·数据库·线性代数·矩阵·架构·模拟退火算法
LOVE️YOU3 小时前
Python 数据结构的本质:位置、对象引用、Hash 与可变性
数据结构·python·哈希算法
不会就选b4 小时前
算法日常・每日刷题--<动态规划>1
java·数据结构·算法
shehuiyuelaiyuehao4 小时前
算法54,链表 两数相加
数据结构·算法·链表
Logic1014 小时前
C语言/数据结构位运算题解:异或XOR找出弹子游戏机中数量为奇数的数字——只出现奇数次
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
阿狗童鞋6 小时前
数据结构与算法实战指南
数据结构·算法
垆边人似月.7 小时前
华为机考题:明明的随机数
数据结构·算法·华为
lusklusklusk8 小时前
Python 四大数据结构详解:元组、列表、集合、字典的特点与增删改查
数据结构·windows·python