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
相关推荐
我想进大厂36 分钟前
图论---朴素Prim(稠密图)
数据结构·c++·算法·图论
我想进大厂41 分钟前
图论---Bellman-Ford算法
数据结构·c++·算法·图论
lkbhua莱克瓦241 小时前
用C语言实现——一个中缀表达式的计算器。支持用户输入和动画演示过程。
c语言·开发语言·数据结构·链表·学习方法·交友·计算器
转基因3 小时前
Codeforces Round 1020 (Div. 3)(题解ABCDEF)
数据结构·c++·算法
Forworder4 小时前
[数据结构]树和二叉树
java·数据结构·intellij-idea·idea
我想进大厂4 小时前
图论---Kruskal(稀疏图)
数据结构·c++·算法·图论
@Aurora.4 小时前
数据结构手撕--【二叉树】
数据结构·算法
悲伤小伞4 小时前
C++_数据结构_详解红黑树
数据结构
前端 贾公子4 小时前
力扣 83 . 删除排序链表中的重复元素:深入解析与实现
数据结构·算法
Y1nhl4 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展