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
相关推荐
琢磨先生David1 天前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
qq_454245031 天前
基于组件与行为的树状节点系统
数据结构·c#
超级大福宝1 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
岛雨QA1 天前
常用十种算法「Java数据结构与算法学习笔记13」
数据结构·算法
weiabc1 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法
wefg11 天前
【算法】单调栈和单调队列
数据结构·算法
岛雨QA1 天前
图「Java数据结构与算法学习笔记12」
数据结构·算法
czxyvX1 天前
020-C++之unordered容器
数据结构·c++
岛雨QA1 天前
多路查找树「Java数据结构与算法学习笔记11」
数据结构·算法
AKA__Zas1 天前
初识基本排序
java·数据结构·学习方法·排序