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
            
相关推荐
傲世仙尊32 分钟前
环形链表找入环点-从相遇到等距的最后一推
数据结构·链表
Nazarick1 小时前
力扣LeetCode热题75题(1)
java·算法·leetcode·力扣
16月6日-晴2 小时前
斐波那契数列题解
算法·leetcode
郝学胜-神的一滴2 小时前
Effective Python 条款47:吃透惰性属性
大数据·开发语言·数据库·人工智能·python·算法·oracle
Keven_113 小时前
算法札记:有限差分
算法
忙里偷闲学python4 小时前
GK2A 林火蔓延预报算法说明
算法
我是伪码农4 小时前
11.21程序设计
数据结构·算法
Tisfy4 小时前
LeetCode 3561.移除相邻字符:栈(相邻相消)
算法·leetcode·字符串·题解·栈·相邻相消
战6174 小时前
Python 基础算法:三种排序、二分查找与递归
开发语言·python·算法
灯澜忆梦5 小时前
并查集(Disjoint Set Union,DSU)
数据结构·算法