leetcode#142. Linked List Cycle II

本文介绍了一种使用快慢指针检测链表中循环开始节点的方法,并提供了详细的Python实现代码。这种方法无需额外空间,适用于未知长度且不可修改的链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up:
Can you solve it without using extra space?
这题回忆满满呀。当初进实验室前,道佳面试我的时候就问了这题。当时临时想的就是最蠢的标记法,或者开数组存储遍历过的节点之类的…显然在不能修改链表和不知道链表有多长的时候,这种做法是不实际的。当时道佳就跟我说了快慢指针的做法,后来也和小嘎嘎讨论过这题,有次还仔细的思考了为啥俩指针速度要差一倍,可惜现在都忘了当初的思考结果了。

Code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        slow = fast = head
        while slow != None and fast != None:
            slow = slow.next
            fast = fast.next
            if fast == None:
                return None
            else:
                fast = fast.next
            if fast == slow:
                break
        if fast == None:
            return None
        while head != fast:
            head = head.next
            fast = fast.next
        return head

Conclusion

网上的解释很多,随便一搜就有,此处只记录个算法。

http://blog.sina.com.cn/s/blog_6a0e04380101a9o2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值