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

剑指offer中的一道题目。具体题目百度一下即可。
自己写了一个双指针法。有漏洞。

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        cur1 = pHead1
        cur2 = pHead2
        while cur1 != cur2:
            if not cur1:
                cur1 = pHead2
            if not cur2:
                cur2 = pHead1
            cur1 = cur1.next
            cur2 = cur2.next
        return cur1

这个代码通过了7/9,下面用例没通过,中间cur1 = cur2,丛头第二次再来循环时,直接退出了。

用例输入
{1,2,3,4,5},{},{}
预期输出
{}
实际输出{2,34,5}

下列代码完美通过

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

#
# 
# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
#
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        cur1 = pHead1
        cur2 = pHead2
        while cur1 != cur2:
            if cur1:
                cur1 = cur1.next
            else:
                cur1 = pHead2
            if cur2:
                cur2 = cur2.next
            else:
                cur2 = pHead1
        return cur1

我思考了一下又对第一个没通过的程序进行了改进,然而还是不对为什么呢??
对比通过的程序:我觉得是没有判断cur2是否为空就直接进行next,这样会导致一种情况。cur2为None就坏起来了!!所以在判断cur1之后,不要操作cur2。把这两个逻辑给分开。
AttributeError: ‘NoneType’ object has no attribute ‘next’

# @param pHead1 ListNode类 
# @param pHead2 ListNode类 
# @return ListNode类
class Solution:
    def FindFirstCommonNode(self , pHead1 , pHead2 ):
        # write code here
        cur1 = pHead1
        cur2 = pHead2
        while cur1 != cur2:
            if not cur1:
                cur1 = pHead2
                cur2 = cur2.next
            if not cur2:
                cur2 = pHead1
                cur1 = cur1.next
            cur1 = cur1.next
            cur2 = cur2.next
        return cur1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值