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
相关推荐
-qOVOp-3 分钟前
408第一季 - 数据结构 - 图II
数据结构
-qOVOp-3 分钟前
408第一季 - 数据结构 - 树与二叉树III
数据结构
lifallen9 分钟前
深入浅出 Arrays.sort(DualPivotQuicksort):如何结合快排、归并、堆排序和插入排序
java·开发语言·数据结构·算法·排序算法
jingfeng5149 分钟前
数据结构排序
数据结构·算法·排序算法
kingmax5421200836 分钟前
CCF GESP202503 Grade4-B4263 [GESP202503 四级] 荒地开垦
数据结构·算法
钮钴禄·爱因斯晨2 小时前
Java 面向对象进阶之多态:从概念到实践的深度解析
java·开发语言·数据结构
AL流云。2 小时前
【优选算法】C++滑动窗口
数据结构·c++·算法
眼镜哥(with glasses)6 小时前
蓝桥杯 国赛2024python(b组)题目(1-3)
数据结构·算法·蓝桥杯
int型码农11 小时前
数据结构第八章(一) 插入排序
c语言·数据结构·算法·排序算法·希尔排序
怀旧,11 小时前
【数据结构】6. 时间与空间复杂度
java·数据结构·算法