相交链表

本文介绍了一种用于查找两个链表交点的有效算法。该算法首先计算两个链表的长度,然后移动较长的链表指针以使两个链表长度相同,最后同步遍历两个链表直至找到相同的节点或到达链表尾部。文章提供了详细的Python实现代码。

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

class Solution:
    def getIntersectionNode(self, headA, headB):
        if headA is None or headB is None:
            return None
        lenA = self.getLength(headA)
        lenB = self.getLength(headB)
        print("lenA is {}, lenB is {}".format(lenA, lenB))
        it = ListNode(0)

        if lenA > lenB:
            it = self.movePointer(headA, lenA - lenB)
            itb = headB
            print("it.val is {}".format(it.val))

            while it:
                if it.val != itb.val:
                    it = it.next
                    itb = itb.next
                else:
                    return it

            if it is None:
                return None
        else:
            it = self.movePointer(headB, lenB - lenA)
            ita = headA
            while it:
                if it.val != ita.val:
                    it = it.next
                    ita = ita.next
                else:
                    return it
            if it is None:
                return None


    def movePointer(self, head, count):
        it = head
        while count > 0:

            if it:
                it = it.next
            count -= 1
        return it



    def getLength(self, head):
        count = 1
        it = head
        if head is None:
            return 0
        while it:
            count += 1
            it = it.next
        return count

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值