- 1.先分别遍历一遍a b链表,求分别的长度
- 2.让长度长的链表先走长的差值
- 3.判断相等就返回,否则返回无
# 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 ):
test1 = ListNode(0)
test2 = ListNode(0)
test1.next,test2.next =pHead1,pHead2
l1,l2 = test1.next,test2.next
len1 = len2 =0
while l1 or l2:
if l1!=None:
len1 = len1+1
l1=l1.next
if l2!= None:
len2 =len2+1
l2= l2.next
l1,l2 = test1.next,test2.next
distance = abs(len1-len2)
while l1!=l2 :
if l1!=None and distance==0:
l1=l1.next
if l2!=None and distance==0:
l2=l2.next
if len1>=len2 and distance!=0:
l1 = l1.next
distance = distance-1
if len1<len2 and distance!=0:
l2 = l2.next
distance = distance-1
if l1==l2:
return l1
else:
return None
# write code here