[Leetcode]Linked List Cycle II

本文介绍了一种高效的方法来确定链表中循环的开始节点。通过使用快慢指针技巧,在不额外使用空间的情况下解决此问题。当快慢指针首次相遇后,将其中一个指针移回头部,然后同时向前移动直到再次相遇即为循环起点。

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

Follow up:

Can you solve it without using extra space?

Linked List Cycle的扩展题,要找到cycle的起始点,还是跟Linked List Cycle那题一样,维护两个指针,fast指针以两倍slow指针的速度往前走 如果两个指针相遇,则有cycle  此时移动slow指针到head节点,这时俩指针离cycle的起点距离一样,两个指针以同样的速度往前走,就会在cycle的起点相遇~

这题的数学分析推导一直没耐心看 仅仅是记住了这种做法  找时间再好好看看


class Solution:
    # @param head, a ListNode
    # @return a list node
    def detectCycle(self, head):
        if head is None or head.next is None: return None
        slow, fast = head, head
        while fast != None and fast.next != None:
            fast, slow = fast.next.next, slow.next
            if fast == slow:
                break
        if fast != slow:
            return None
        slow = head
        while slow != fast:
            slow, fast = slow.next, fast.next
        return slow


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值