Leetcode 142. 环形链表 II

注意的点:

1、注意里面的判断条件,虽然代码少但是其实逻辑很多。

解法:快慢指针

python 复制代码
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:

        # 快慢指针
        slow, fast = head, head

        if not head: return None

        while fast.next and fast.next.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast: break # 得放在后面
        
        if not fast.next or not fast.next.next: 
            return None

        slow = head
        while slow != fast:
            slow = slow.next
            fast = fast.next

        return fast
            
相关推荐
程序猿进阶2 小时前
如何在 Visual Studio Code 中反编译具有正确行号的 Java 类?
java·ide·vscode·算法·面试·职场和发展·架构
Eloudy2 小时前
一个编写最快,运行很慢的 cuda gemm kernel, 占位 kernel
算法
程序猿练习生2 小时前
C++速通LeetCode中等第5题-无重复字符的最长字串
开发语言·c++·leetcode
king_machine design2 小时前
matlab中如何进行强制类型转换
数据结构·算法·matlab
西北大程序猿2 小时前
C++ (进阶) ─── 多态
算法
无名之逆2 小时前
云原生(Cloud Native)
开发语言·c++·算法·云原生·面试·职场和发展·大学期末
头发尚存的猿小二2 小时前
树——数据结构
数据结构·算法
好蛊2 小时前
第 2 课 春晓——cout 语句
c++·算法
山顶夕景2 小时前
【Leetcode152】分割回文串(回溯 | 递归)
算法·深度优先·回溯
紫钺-高山仰止3 小时前
【Matlab】matlab 结构体使用方法
数据结构·算法·matlab