剑指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,3,4,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