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
相关推荐
博大世界26 分钟前
matlab结构体数组定义
数据结构·算法
罗湖老棍子3 小时前
强迫症冒险家的任务清单:字典序最小拓扑排序
数据结构·算法·图论·拓扑排序
数智工坊3 小时前
【操作系统-文件管理】
数据结构·数据库
芒克芒克4 小时前
数组去重进阶:一次遍历实现最多保留指定个数重复元素(O(n)时间+O(1)空间)
数据结构·算法
Fcy6485 小时前
⽤哈希表封装unordered_map和unordered_set(C++模拟实现)
数据结构·c++·散列表
一分之二~5 小时前
二叉树--层序遍历(迭代和递归)
数据结构·c++·算法·leetcode
captain3766 小时前
Java-链表
java·开发语言·链表
散峰而望7 小时前
【基础算法】高精度运算深度解析与优化
数据结构·c++·算法·链表·贪心算法·推荐算法
C雨后彩虹8 小时前
中文分词模拟器
java·数据结构·算法·华为·面试
Remember_9938 小时前
【LeetCode精选算法】二分查找专题二
java·数据结构·算法·leetcode·哈希算法