class LNode:
def __init__(self):
self.data = None
self.next = None
def IsIntersect(head1, head2):
if head1 == None or head1.next == None or head2 == None or head2.next == None or head1 == head2:
return None
tmp1 = head1.next
tmp2 = head2.next
n1, n2 = 1, 1
while tmp1.next != None:
tmp1 = tmp1.next
n1 += 1
while tmp2.next != None:
tmp2 = tmp2.next
n2 += 1
if tmp1 == tmp2:
if n1 > n2 :
while n1 - n2 > 0:
head1 = head1.next
n1 -= 1
if n2 >n1 :
while n2 - n1 >0:
head2 = head2.next
n2 -= 1
while head1 != head2:
head1 = head1.next
head2 = head2.next
return head1
else:
return None
if __name__ == '__main__':
head1 = LNode()
head2 = LNode()
cur = head1
i= 1
while i<8 :
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
if i==5 :
p = tmp
i += 1
cur = head2
i= 1
while i<5 :
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 1
cur.next = p
interNode = IsIntersect(head1,head2)
if interNode is not None:
print('两个链表相交点为:'+str(interNode.data))
else:
print('不相交')
![运行结果](https://i-blog.csdnimg.cn/blog_migrate/adf0b96f6d0368994397285a9dab50b7.png)