leetcode之Linked List Cycle II

本文介绍了一种算法用于在循环链表中找到结合点,通过计算节点位置和环大小来实现。详细解释了算法步骤,并提供了代码实现。

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

这题在I的基础上不仅要判断,更要找出来是哪个节点开始结合。采用的方法是计算出第一次相遇的时候每次挪一步的那个一共走了x步,再算出来环的大小y。那么x - y就等于从头开始走的时候,距离结合点的距离等于相遇点的距离的那个点。然后2个点一起走,相遇的那个点就一定是结合点啦。代码如下:
# 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
        """
        if not head:
            print '1111'
            return None
        if not head.next:
            return None
        twostep = head.next.next
        distance1 = 0
        left = head
        #distance1是相遇前一共走了多少步,cycle是环的大小。
        while True:
            if head.next == twostep:
                distance1 = distance1 + 1
                cycle = 0
                head1 = head.next
                while True:
                    if head1.next != head.next:
                        cycle = cycle + 1
                        head1 = head1.next
                    else:
                        cycle = cycle + 1
                        for i in range(distance1 - cycle):
                            left = left.next
                        while True:
                            if left == head.next:
                                return left
                            else:
                                left = left.next
                                head = head.next
            else:
                head = head.next
                distance1 = distance1 + 1
                if not twostep:
                    return None
                elif not twostep.next:
                    return None
                else:
                    twostep = twostep.next.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值