两个链表的第一个公共节点

Class ListNode(object):
      def __init__(self,x):
          self.val=x
          self.next=None
#前面的节点不相同,走到相同的位置
        p1=headA
        p2=headB
        lA,lB=[],[]
        while p1:
            lA.append(p1.val)
            p1=p1.next
        while p2:
            lB.append(p2.val)
            p2=p2.next
        # 挑出长链和短链
        l_A=len(lA)
        l_B=len(lB)
        if l_A==l_B==1:
            if headA.val==headB.val:
                return headA
            else:
                return None
        else:
            while l_A!=l_B:
                if l_A>l_B:
                    headA=headA.next
                    l_A-=1
                if l_A<l_B:
                    headB=headB.next
                    l_B-=1
            # 此时两个链表等长
            while l_A:
                if headA==headB:
                    return headA
                else:
                    headA=headA.next
                    headB=headB.next
            return None

官方解答最简单且不用考虑边界:

由于两个链表相交,则一定有一段等长的链表c,不相交的链表长度分别为L1,L2,因此,当且仅当两个链表均走L1+L2+C步时刚好同时走到第一个节点。

        node1,node2=headA,headB
        while node1!=node2:
            node1=node1.next if node1 else headB
            node2=node2.next if node2 else headA
        return node1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值