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
            
相关推荐
yi.Ist12 分钟前
数据结构 —— 键值对 map
数据结构·算法
s1533515 分钟前
数据结构-顺序表-猜数字
数据结构·算法·leetcode
Coding小公仔18 分钟前
LeetCode 8. 字符串转换整数 (atoi)
算法·leetcode·职场和发展
GEEK零零七23 分钟前
Leetcode 393. UTF-8 编码验证
算法·leetcode·职场和发展·二进制运算
DoraBigHead1 小时前
小哆啦解题记——异位词界的社交网络
算法
木头左2 小时前
逻辑回归的Python实现与优化
python·算法·逻辑回归
lifallen6 小时前
Paimon LSM Tree Compaction 策略
java·大数据·数据结构·数据库·算法·lsm-tree
web_Hsir9 小时前
vue3.2 前端动态分页算法
前端·算法
地平线开发者11 小时前
征程 6M 部署 Omnidet 感知模型
算法·自动驾驶
秋说11 小时前
【PTA数据结构 | C语言版】线性表循环右移
c语言·数据结构·算法