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
相关推荐
Gorgous—l4 分钟前
数据结构算法学习:LeetCode热题100-动态规划篇(下)(单词拆分、最长递增子序列、乘积最大子数组、分割等和子集、最长有效括号)
数据结构·学习·算法
Remember_9931 小时前
【LeetCode精选算法】滑动窗口专题一
java·数据结构·算法·leetcode·哈希算法
Lueeee.1 小时前
v4l2驱动开发
数据结构·驱动开发·b树
漫随流水2 小时前
leetcode回溯算法(77.组合)
数据结构·算法·leetcode·回溯算法
超级大福宝3 小时前
【力扣200. 岛屿数量】的一种错误解法(BFS)
数据结构·c++·算法·leetcode·广度优先
iAkuya4 小时前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
一分之二~6 小时前
回溯算法--解数独
开发语言·数据结构·c++·算法·leetcode
不如语冰7 小时前
AI大模型入门1.1-python基础-数据结构
数据结构·人工智能·pytorch·python·cnn
未来之窗软件服务7 小时前
计算机等级考试—哈希线性探测解答—东方仙盟
数据结构·哈希算法·散列表·计算机软考·仙盟创梦ide·东方仙盟
苦藤新鸡7 小时前
18.矩阵同行同列全置零
数据结构·c++·算法·力扣