leetcode 141.环形链表

看了题解:一个指针每次跑两步,一个指针每次跑一步,如果是环形链表一定会相遇,不会错过。

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

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        if head == None:
            return False
        fast = head.next
        slow = head
        

        while(fast != slow and fast !=None):
            if fast.next==None:
                return False
            fast = fast.next.next
            slow = slow.next
        
        return fast==slow

题解代码:

python 复制代码
class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow = fast = head  # 乌龟和兔子同时从起点出发
        while fast and fast.next:
            slow = slow.next  # 乌龟走一步
            fast = fast.next.next  # 兔子走两步
            if fast is slow:  # 兔子追上乌龟(套圈),说明有环
                return True
        return False  # 访问到了链表末尾,无环

作者:灵茶山艾府
链接:https://leetcode.cn/problems/linked-list-cycle/solutions/1999269/mei-xiang-ming-bai-yi-ge-shi-pin-jiang-t-c4sw/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
相关推荐
ZhengEnCi7 小时前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi8 小时前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽8 小时前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187919 小时前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python
To_OC19 小时前
LC 207 课程表:刚学图论那会儿,我连这是拓扑排序都没看出来
javascript·算法·leetcode
To_OC19 小时前
LC 208 实现 Trie 前缀树:曾被名字劝退,写完发现是送分题
javascript·算法·leetcode
Warson_L1 天前
Python `Annotated` 与 LangGraph Reducer 学习笔记
python
韩师傅1 天前
海天线算法的前世今生
python·计算机视觉
韩师傅1 天前
当你的甲方设备过烂,要如何快速出效果?
python·计算机视觉
Warson_L1 天前
LangGraph的MessageState and HumanMessage
python